Repository navigation
fix(cold-store-reaper): rebuild turso dumps with repeated tables and vector indexes #12028
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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_]*)' | ||
| ) | ||
|
|
||
|
|
||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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 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() | ||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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 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() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 asCREATE TABLE IF NOT EXISTS foo$one(x);andCREATE TABLE IF NOT EXISTS foo$two(y);are therefore both recorded as tablefoo. 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 👍 / 👎.