Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions pkgs/cold-store-reaper/scripts/dedupe_dump.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Drop a table block that a libsql /dump repeats byte for byte (#12000).

Reads a SQL dump on stdin and writes it to stdout. libsql's /dump can
emit a table twice: the atlas database's vector table
(``vec_snowflake_m_v2_768_f32``, which carries a ``libsql_vector_idx``
index) came out as ``CREATE TABLE IF NOT EXISTS ...`` plus all of its
rows, then the same ``CREATE TABLE IF NOT EXISTS ...`` and every row
again, in the same order. The live table has no duplicate keys, so a
plain sqlite3 rebuild stops on the second copy's first primary key.

The filter recognises a block as a ``CREATE TABLE [IF NOT EXISTS] <name>``
statement on one line followed by the ``INSERT INTO <name> VALUES``
lines right after it. For every table it keeps a running SHA-256 of
that first block's INSERT lines and their count. When a second
``CREATE TABLE`` for a table already seen arrives:

* the CREATE statement must be byte-identical to the first one, and
* the INSERT lines that follow are consumed without being written,
and their hash and count must equal the first block's.

When both hold, the repeat is dropped and one line on stderr says so
(table name and row count only, never row values). When either does
not hold, the filter exits 1 with a message: rows that differ are a
real conflict, and dropping them silently would lose data. Every other
line passes through byte-identical.

Constant memory: one digest, one count and one CREATE line per table,
never the rows themselves.
"""

import hashlib
import re
import sys

CREATE = re.compile(
rb'^CREATE TABLE (?:IF NOT EXISTS )?("(?:[^"]|"")+"|\'(?:[^\']|\'\')+\'|[A-Za-z_][A-Za-z0-9_]*)'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Match complete identifiers before comparing table definitions

For valid unquoted SQLite identifiers containing $ or non-ASCII characters, this regex captures only the ASCII prefix without checking that the identifier ends there. Distinct declarations such as CREATE TABLE IF NOT EXISTS foo$one(x); and CREATE TABLE IF NOT EXISTS foo$two(y); are therefore both recorded as table foo. The second declaration triggers the differing-definition error and aborts an otherwise valid export even though there is no repeated table; these declarations passed through the previous pipeline unchanged. Match the complete identifier, or leave unsupported identifier forms untouched rather than registering a partial name.

Useful? React with 👍 / 👎.

)


def table_name(token):
"""The bare table name of a CREATE TABLE name token."""
if token[:1] in (b'"', b"'"):
quote = token[:1]
return token[1:-1].replace(quote + quote, quote)
return token


def insert_prefixes(name):
"""The INSERT line prefixes a dump uses for this table."""
quoted = b'"' + name.replace(b'"', b'""') + b'"'
prefixes = [b"INSERT INTO " + quoted + b" VALUES"]
if re.fullmatch(rb"[A-Za-z_][A-Za-z0-9_]*", name):
prefixes.append(b"INSERT INTO " + name + b" VALUES")
return tuple(prefixes)


class Block:
"""One table's CREATE statement and the INSERT lines right after it."""

def __init__(self, name):
self.name = name
self.prefixes = insert_prefixes(name)
self.create = [] # the CREATE statement's lines (it may span several)
self.digest = hashlib.sha256()
self.count = 0

@property
def label(self):
return self.name.decode(errors="replace")

def owns(self, line):
return line.startswith(self.prefixes)

def add(self, line):
self.digest.update(line)
self.count += 1

def same_rows(self, other):
return (self.count, self.digest.digest()) == (other.count, other.digest.digest())


def ends_statement(line):
return line.rstrip(b"\r\n \t").endswith(b";")


def fail(message):
sys.stderr.write(f"dedupe_dump: {message}\n")
sys.exit(1)


def finish_repeat(original, again):
if not original.same_rows(again):
fail(
f"table {original.label} is dumped twice with different rows "
f"({original.count} rows, then {again.count}); not dropping either copy"
)
sys.stderr.write(
f"dedupe_dump: dropped a repeated copy of table {original.label} "
f"({again.count} rows identical to the first copy)\n"
)


def main():
out = sys.stdout.buffer
first = {} # table name -> its first Block
block = None # the Block whose CREATE or INSERT lines are being read
original = None # set while block is a repeat of this first Block
in_create = False
for line in sys.stdin.buffer:
if block is not None:
if in_create:
block.create.append(line)
in_create = not ends_statement(line)
if not in_create and original is not None and block.create != original.create:
fail(
f"table {block.label} is created twice with different "
"definitions; not dropping either copy"
)
if original is None:
out.write(line)
continue
if block.owns(line):
block.add(line)
if original is None:
out.write(line)
continue
if original is not None:
finish_repeat(original, block)
block = original = None
match = CREATE.match(line)
Comment on lines +130 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Track SQL literal context before dropping repeated CREATEs

When a multiline text value contains a line identical to an earlier empty table's CREATE statement, this physical-line match mistakes the text for a repeated table block. For example, after CREATE TABLE IF NOT EXISTS empty (x);, a later INSERT INTO notes VALUES('before\nCREATE TABLE IF NOT EXISTS empty (x);\nafter'); loses the embedded CREATE line: both apparent empty-table blocks have matching zero-row digests. The resulting INSERT remains valid, so the export passes COMMIT and integrity checks while silently corrupting the stored text. Track statement/string-literal context before recognizing table blocks; the new vector-index filter needs the same protection before rewriting physical lines.

Useful? React with 👍 / 👎.

if match:
name = table_name(match.group(1))
block = Block(name)
block.create.append(line)
in_create = not ends_statement(line)
if name in first:
original = first[name]
if not in_create and block.create != original.create:
fail(
f"table {block.label} is created twice with different "
"definitions; not dropping either copy"
)
continue # the repeated CREATE is dropped with its rows
first[name] = block
out.write(line)
if block is not None and original is not None:
if in_create:
fail(f"table {block.label}: the dump ends inside a repeated CREATE statement")
finish_repeat(original, block)
out.flush()


if __name__ == "__main__":
main()
23 changes: 22 additions & 1 deletion pkgs/cold-store-reaper/scripts/export-turso.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
# dump through scripts/repair_dump.py (libsql does not escape single
# quotes inside the sqlite_schema INSERTs that register virtual
# tables, so FTS5 databases are otherwise unparseable — #1391),
# scripts/dedupe_dump.py (libsql can dump a table twice; an exact
# repeat is dropped, a differing one fails the export — #12000) and
# scripts/vector_index_dump.py (stock sqlite3 cannot build a libsql
# vector index, so its CREATE INDEX is kept as a recorded statement;
# the index data stays in its shadow tables — #12000),
# require the filtered dump to end in COMMIT; (a truncated dump
# otherwise rebuilds into an integrity-clean but partial database),
# stream it through
Expand Down Expand Up @@ -251,7 +256,23 @@ PY
# streams the dump (constant memory, one statement buffered) and
# rewrites only verifiably mis-escaped schema literals with proper
# '' doubling; everything else passes through byte-identical.
if ! python3 "${SCRIPT_DIR}/repair_dump.py" <"${dump_sql}" >"${filtered_sql}"; then
#
# Repeat pass (#12000): libsql's /dump can emit a table twice (the
# atlas vector table came out whole, then whole again, byte for
# byte), and the rebuild then stops on the second copy's first
# primary key. dedupe_dump.py drops a repeated copy only when its
# CREATE statement and every row match the first copy exactly, and
# fails (exit 1) when they differ, so no row is dropped silently.
#
# Vector index pass (#12000): a libsql vector index is dumped as
# CREATE INDEX ... (libsql_vector_idx(...)), which stock sqlite3
# cannot run, so the rebuild died on the dump's last statement.
# vector_index_dump.py records that statement in the table
# cold_store_libsql_vector_indexes instead; the index's data is in
# its shadow tables, which are dumped and rebuilt as plain tables.
if ! python3 "${SCRIPT_DIR}/repair_dump.py" <"${dump_sql}" |
python3 "${SCRIPT_DIR}/dedupe_dump.py" |
python3 "${SCRIPT_DIR}/vector_index_dump.py" >"${filtered_sql}"; then
echo "turso export: ERROR: ${name}: dump repair filter failed" >&2
return 1
fi
Expand Down
80 changes: 80 additions & 0 deletions pkgs/cold-store-reaper/scripts/vector_index_dump.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Keep a libsql vector index as a recorded statement (#12000).

Reads a SQL dump on stdin and writes it to stdout. libsql's /dump ends
a database with a vector index on a statement such as::

CREATE INDEX vec_idx ON vec (libsql_vector_idx(v));

``libsql_vector_idx`` exists only in libsql, so the stock sqlite3 CLI
that rebuilds the export stops there ("no such function"), after every
row has loaded, and the whole export fails. The index's data is not
lost by skipping the statement: libsql keeps it in ordinary tables
(``<index>_shadow`` and ``libsql_vector_meta_shadow``), and those are
dumped and rebuilt like any other table.

So each such ``CREATE INDEX`` line is replaced by a row in a small
table, ``cold_store_libsql_vector_indexes(name, sql)``, holding the
statement exactly as libsql dumped it. Restoring into libsql: drop the
index's shadow table and its ``libsql_vector_meta_shadow`` row, then run
the recorded statement, and libsql rebuilds the index from the vectors.

Only a single-line ``CREATE INDEX`` whose text calls
``libsql_vector_idx(`` is rewritten. One that does not end on its line
fails the filter (exit 1) rather than being guessed at. Every other
line passes through byte-identical, so a dump without a vector index
comes out unchanged.
"""

import re
import sys

TABLE = b"cold_store_libsql_vector_indexes"
VECTOR_INDEX = re.compile(
rb'^CREATE INDEX (?:IF NOT EXISTS )?("(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*) ON .*'
rb"\blibsql_vector_idx\s*\(",
re.IGNORECASE,
)


def literal(raw):
return b"'" + raw.replace(b"'", b"''") + b"'"


def index_name(token):
if token[:1] == b'"':
return token[1:-1].replace(b'""', b'"')
return token


def main():
out = sys.stdout.buffer
created = False
for line in sys.stdin.buffer:
Comment on lines +50 to +53

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject unexpected arguments before processing either filter

Both new scripts enter their stdin-processing loops without inspecting command-line arguments, so an invocation with an unknown flag or stray positional silently performs the transformation and exits successfully rather than reporting a usage error. This violates the operator-script argument contract in AGENTS.md, which requires strict argument validation before output or other effects. Declare that these filters accept no arguments and reject unexpected arguments with a nonzero exit before consuming stdin or writing stdout.

AGENTS.md reference: AGENTS.md:L47-L51

Useful? React with 👍 / 👎.

match = VECTOR_INDEX.match(line)
if not match:
out.write(line)
continue
statement = line.rstrip(b"\r\n")
if not statement.rstrip(b" \t").endswith(b");"):
sys.stderr.write(
"vector_index_dump: a libsql vector index statement does not end "
"on its line; not rewriting it\n"
)
sys.exit(1)
name = index_name(match.group(1))
if not created:
out.write(
b"CREATE TABLE IF NOT EXISTS " + TABLE + b"(name TEXT PRIMARY KEY, sql TEXT NOT NULL);\n"
)
created = True
out.write(b"INSERT INTO " + TABLE + b" VALUES(" + literal(name) + b"," + literal(statement) + b");\n")
sys.stderr.write(
f"vector_index_dump: kept libsql vector index {name.decode(errors='replace')} "
f"as a recorded statement in {TABLE.decode()}\n"
)
out.flush()


if __name__ == "__main__":
main()
Loading