Files
turso/bindings/python/tests/test_database_sync.py
Jussi Saurio b46ded716e bindings/python: connect sync tests to the local server over 127.0.0.1
On Windows the Python sync tests took ~5 min per test file, against
~42 s on macOS. The time goes into connections, not work: e.g.
test_bootstrap 10.16 s on Windows vs 0.23 s on macOS, and
test_partial_sync_segment_size (many requests) 122.9 s vs 1.05 s, while
the data-heavy test_pull_bytes_threshold took about the same on both.

The local sync server listens on 0.0.0.0 (IPv4 only), but the tests
connected to "localhost". Windows resolves localhost to ::1 first, and a
refused connection there takes about 2 s before the client falls back to
127.0.0.1, on every new connection. That fits the numbers above; the
Windows CI timings of this change will confirm it.

Connect to 127.0.0.1 directly. The persisted-URL assertion now checks for
the server URL itself instead of the "http://localhost" prefix.
2026-10-14 09:36:51 +03:00

306 lines
12 KiB
Python

import logging
import multiprocessing
import os
import tempfile
import threading
import time
import turso
import turso.sync
from .utils import CountingProxy, TursoServer
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", force=True)
def test_bootstrap():
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
server.db_sql("SELECT * FROM t")
conn = turso.sync.connect(":memory:", server.db_url())
rows = conn.execute("SELECT * FROM t").fetchall()
assert rows == [("hello",), ("turso",), ("sync",)]
def test_pull():
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
server.db_sql("SELECT * FROM t")
conn = turso.sync.connect(":memory:", server.db_url())
rows = conn.execute("SELECT * FROM t").fetchall()
assert rows == [("hello",), ("turso",), ("sync",)]
server.db_sql("INSERT INTO t VALUES ('pull works')")
rows = conn.execute("SELECT * FROM t").fetchall()
assert rows == [("hello",), ("turso",), ("sync",)]
assert conn.pull()
rows = conn.execute("SELECT * FROM t").fetchall()
assert rows == [("hello",), ("turso",), ("sync",), ("pull works",)]
assert not conn.pull()
def test_push():
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
server.db_sql("SELECT * FROM t")
conn = turso.sync.connect(":memory:", server.db_url())
rows = conn.execute("SELECT * FROM t").fetchall()
assert rows == [("hello",), ("turso",), ("sync",)]
conn.execute("INSERT INTO t VALUES ('push works')")
conn.commit()
r1 = server.db_sql("SELECT * FROM t")
assert r1 == [["hello"], ["turso"], ["sync"]]
conn.push()
r2 = server.db_sql("SELECT * FROM t")
assert r2 == [["hello"], ["turso"], ["sync"], ["push works"]]
def test_checkpoint():
# turso.setup_logging(level=logging.DEBUG)
with TursoServer() as server:
conn = turso.sync.connect(":memory:", remote_url=server.db_url())
conn.execute("CREATE TABLE t(x)")
conn.commit()
for i in range(1024):
conn.execute(f"INSERT INTO t VALUES ({i})")
if i % 4 == 3:
conn.commit()
stats1 = conn.stats()
conn.checkpoint()
stats2 = conn.stats()
assert stats1.main_wal_size > 1024 * 1024
assert stats1.revert_wal_size == 0
assert stats2.main_wal_size == 0
assert stats2.revert_wal_size < 8 * 1024
conn.push()
assert server.db_sql("SELECT SUM(x) FROM t") == [[f"{1024 * 1023 // 2}"]]
def test_partial_sync():
# turso.setup_logging(level=logging.DEBUG)
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 2000)")
conn_full = turso.sync.connect(":memory:", remote_url=server.db_url())
assert conn_full.execute("SELECT LENGTH(x) FROM t LIMIT 1").fetchall() == [(1024,)]
assert conn_full.stats().network_received_bytes > 2000 * 1024
assert conn_full.execute("SELECT SUM(LENGTH(x)) FROM t").fetchall() == [(2000 * 1024,)]
conn_partial = turso.sync.connect(
":memory:",
remote_url=server.db_url(),
partial_sync_experimental=turso.sync.PartialSyncOpts(
bootstrap_strategy=turso.sync.PartialSyncPrefixBootstrap(length=128 * 1024),
),
)
assert conn_partial.execute("SELECT LENGTH(x) FROM t LIMIT 1").fetchall() == [(1024,)]
assert conn_partial.stats().network_received_bytes < 256 * (1024 + 10)
start = time.time()
assert conn_partial.execute("SELECT SUM(LENGTH(x)) FROM t").fetchall() == [(2000 * 1024,)]
print(time.time() - start)
assert conn_partial.stats().network_received_bytes > 2000 * 1024
def test_partial_sync_segment_size():
# turso.setup_logging(level=logging.DEBUG)
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 256)")
conn_full = turso.sync.connect(":memory:", remote_url=server.db_url())
assert conn_full.execute("SELECT LENGTH(x) FROM t LIMIT 1").fetchall() == [(1024,)]
assert conn_full.stats().network_received_bytes > 256 * 1024
assert conn_full.execute("SELECT SUM(LENGTH(x)) FROM t").fetchall() == [(256 * 1024,)]
conn_partial = turso.sync.connect(
":memory:",
remote_url=server.db_url(),
partial_sync_experimental=turso.sync.PartialSyncOpts(
bootstrap_strategy=turso.sync.PartialSyncPrefixBootstrap(length=128 * 1024),
segment_size=4 * 1024,
),
)
assert conn_partial.execute("SELECT LENGTH(x) FROM t LIMIT 1").fetchall() == [(1024,)]
assert conn_partial.stats().network_received_bytes < 128 * 1024 * 1.5
start = time.time()
assert conn_partial.execute("SELECT SUM(LENGTH(x)) FROM t").fetchall() == [(256 * 1024,)]
print(time.time() - start)
assert conn_partial.stats().network_received_bytes > 256 * 1024
def test_partial_sync_prefetch():
# turso.setup_logging(level=logging.DEBUG)
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 2000)")
conn_full = turso.sync.connect(":memory:", remote_url=server.db_url())
assert conn_full.execute("SELECT LENGTH(x) FROM t LIMIT 1").fetchall() == [(1024,)]
assert conn_full.stats().network_received_bytes > 2000 * 1024
assert conn_full.execute("SELECT SUM(LENGTH(x)) FROM t").fetchall() == [(2000 * 1024,)]
conn_partial = turso.sync.connect(
":memory:",
remote_url=server.db_url(),
partial_sync_experimental=turso.sync.PartialSyncOpts(
bootstrap_strategy=turso.sync.PartialSyncPrefixBootstrap(length=128 * 1024),
segment_size=4 * 1024,
prefetch=True,
),
)
assert conn_partial.execute("SELECT LENGTH(x) FROM t LIMIT 1").fetchall() == [(1024,)]
assert conn_partial.stats().network_received_bytes < 1200 * 1024
start = time.time()
assert conn_partial.execute("SELECT SUM(LENGTH(x)) FROM t").fetchall() == [(2000 * 1024,)]
print(time.time() - start)
assert conn_partial.stats().network_received_bytes > 2000 * 1024
def run_full(path: str, remote_url: str, barrier: any):
barrier.wait(timeout=60)
try:
print(turso.sync.connect(path, remote_url=remote_url))
except Exception as e:
print("valid error", e, type(e), isinstance(e, turso.Error), turso.Error)
def test_bootstrap_concurrency():
# turso.setup_logging(level=logging.DEBUG)
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 2000)")
with tempfile.TemporaryDirectory(prefix="pyturso-") as dir:
path = os.path.join(dir, "local.db")
print(path)
barrier = multiprocessing.Barrier(2)
t1 = multiprocessing.Process(target=run_full, args=(path, server.db_url(), barrier))
t2 = multiprocessing.Process(target=run_full, args=(path, server.db_url(), barrier))
t1.start()
t2.start()
t1.join(timeout=120)
t2.join(timeout=120)
if t1.is_alive():
t1.kill()
t1.join()
if t2.is_alive():
t2.kill()
t2.join()
assert t1.exitcode == 0, f"t1 exitcode: {t1.exitcode}"
assert t2.exitcode == 0, f"t2 exitcode: {t2.exitcode}"
def test_concurrent_open_existing_replica():
# Opening an already-hydrated replica from many threads at once must
# always succeed: opens read (and, when the configuration changed, write)
# the shared metadata file, and a non-atomic write lets a concurrent
# reader observe an empty or truncated file ("meta must be initialized
# before open" / "deserialization error").
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t VALUES (42)")
with tempfile.TemporaryDirectory(prefix="pyturso-") as dir:
path = os.path.join(dir, "local.db")
conn = turso.sync.connect(path, remote_url=server.db_url())
conn.pull()
conn.close()
k = 8
errors = []
def open_and_read():
try:
c = turso.sync.connect(path, remote_url=server.db_url())
assert c.execute("SELECT * FROM t").fetchall() == [(42,)]
c.close()
except Exception as e:
errors.append(e)
for _ in range(3):
threads = [threading.Thread(target=open_and_read) for _ in range(k)]
for t in threads:
t.start()
for t in threads:
t.join(timeout=120)
assert not errors, f"concurrent opens failed: {errors[0]}"
def test_configuration_persistence():
with TursoServer() as server:
server.db_sql("CREATE TABLE t(x)")
server.db_sql("INSERT INTO t VALUES (42)")
with tempfile.TemporaryDirectory(prefix="pyturso-") as dir:
path = os.path.join(dir, "local.db")
print(path)
conn1 = turso.sync.connect(path, remote_url=server.db_url())
assert conn1.execute("SELECT * FROM t").fetchall() == [(42,)]
conn1.close()
server.db_sql("INSERT INTO t VALUES (43)")
assert server.db_url() in open(f"{path}-info", "r").read()
conn2 = turso.sync.connect(path)
conn2.pull()
assert conn2.execute("SELECT * FROM t").fetchall() == [(42,), (43,)]
conn2.close()
def test_pull_bytes_threshold():
# Verify that pull_bytes_threshold is propagated to the sync engine: when set,
# the bootstrap download is split into multiple /pull-updates HTTP requests
# instead of a single round-trip.
with TursoServer() as server:
server.db_sql("CREATE TABLE big(x INTEGER PRIMARY KEY, y BLOB)")
server.db_sql("INSERT INTO big SELECT value, randomblob(1024) FROM generate_series(1, 50)")
# bootstrap fetches the seeded db into a fresh in-memory client through a
# counting proxy and returns how many /pull-updates requests it issued.
def bootstrap(threshold):
with CountingProxy(server.db_url(), "/pull-updates") as proxy:
conn = turso.sync.connect(":memory:", proxy.url(), pull_bytes_threshold=threshold)
assert conn.execute("SELECT COUNT(*) FROM big").fetchall() == [(50,)]
conn.close()
return proxy.count
# Default bootstrap is a single round-trip; an 8KB threshold (2 pages per
# chunk) over a multi-page db must split into strictly more requests. If
# the setting were not propagated both runs would issue the same count.
without_threshold = bootstrap(None)
with_threshold = bootstrap(8192)
assert with_threshold > without_threshold
assert with_threshold > 1