diff --git a/pkgs/cold-store-reaper/scripts/repair_dump.py b/pkgs/cold-store-reaper/scripts/repair_dump.py index eef3dfeb2f..057cafd230 100644 --- a/pkgs/cold-store-reaper/scripts/repair_dump.py +++ b/pkgs/cold-store-reaper/scripts/repair_dump.py @@ -31,8 +31,18 @@ body's ``SELECT RAISE(ABORT, 'bad');`` — therefore does not split the statement. An unterminated statement at EOF is flushed unchanged — the caller's truncation guard judges the filtered stream. + +One bound keeps the constant-memory promise honest (#6525): a +candidate that grows past MAX_CANDIDATE_BYTES without terminating +is flushed unchanged and the rest of its statement streams through +line by line (the end is still recognised, so the following +statement is processed normally). Such a statement is not repaired +— repair requires holding it — but an unterminated or pathological +candidate can no longer grow the filter's memory to the size of +the remaining dump while emitting nothing. """ +import os import re import sys @@ -42,6 +52,25 @@ COMMA = 0x2C # , SPACE = b" \t\r\n" # A line that begins a new top-level dump statement (column 0). +# The largest candidate statement held for repair, in bytes. Real +# sqlite_schema statements (a table, view, trigger or index +# definition) are orders of magnitude smaller; the cap exists for +# the pathological candidate, not for them. Overridable for tests +# and for an operator repairing a genuinely huge schema. +def _max_candidate_bytes(): + raw = os.environ.get("REPAIR_DUMP_MAX_CANDIDATE_BYTES") + if raw: + try: + value = int(raw) + except ValueError: + value = 0 + if value > 0: + return value + return 8 * 1024 * 1024 + + +MAX_CANDIDATE_BYTES = _max_candidate_bytes() + TOP_LEVEL_START = re.compile( rb"(?:INSERT|PRAGMA|COMMIT|BEGIN|CREATE|DELETE|UPDATE|DROP|ALTER|" rb"REPLACE|ANALYZE|VACUUM|--)", @@ -152,6 +181,22 @@ def repair_chunk(chunk): return repair_statement(core) + newline +def _next_line_starts_new(next_line): + """Whether next_line begins a new top-level statement (or is EOF). + + The lookahead half of ends_statement(), shared with pass-through + mode: there the current line must never be parsed standalone -- + an interior line of an over-cap statement can itself parse as a + complete schema INSERT while the outer literal is still open. + """ + if next_line is None: + return True + return bool( + next_line.lstrip().startswith(SCHEMA_INSERT) + or TOP_LEVEL_START.match(next_line) + ) + + def ends_statement(chunk, next_line): """Whether the buffered chunk (last line ends in ``');``) is complete. @@ -167,12 +212,7 @@ def ends_statement(chunk, next_line): end = parse_literal(text, pos) if end is not None and text[end:] == b");": return True - if next_line is None: - return True - return bool( - next_line.lstrip().startswith(SCHEMA_INSERT) - or TOP_LEVEL_START.match(next_line) - ) + return _next_line_starts_new(next_line) def _final_literal_start(text): @@ -193,27 +233,113 @@ def _final_literal_start(text): return pos +class _LiteralTracker: + """Streaming SQL string-literal state for a pass-through candidate. + + Oracle: a correctly escaped statement -- the kind whose end the + buffered test in ends_statement() recognises from the statement + head, which pass-through no longer holds. Feeding the statement's + bytes in order tracks whether the scan is inside a string + literal: a '' pair inside a literal is an escaped quote, a lone + ' closes it. The state is O(1) -- the over-cap statement itself + is never retained (#6525) -- and it recognises the statement's + end from the statement's own bytes, independently of the next + line (which may be blank, defeating the top-level fallback in + ends_statement()). + """ + + def __init__(self): + self.in_literal = False + self._pending_quote = False + + def feed(self, data): + for byte in data: + if self._pending_quote: + self._pending_quote = False + if byte == QUOTE: + continue # '' inside a literal: an escaped quote + self.in_literal = False + if self.in_literal: + if byte == QUOTE: + self._pending_quote = True + elif byte == QUOTE: + self.in_literal = True + + @property + def outside_literal(self): + return not self.in_literal and not self._pending_quote + + def main(): out = sys.stdout.buffer buffered = None + buffered_bytes = 0 + passthrough = False + tracker = None lines = iter(sys.stdin.buffer) line = next(lines, None) while line is not None: next_line = next(lines, None) - if buffered is not None: + if passthrough: + # The rest of an over-cap candidate streams through + # unchanged; only its end is still recognised, so the + # statement after it is processed normally. The end is + # recognised from the statement's own bytes (the literal + # tracker) or from the next line starting a new statement + # -- never by parsing the current line standalone: an + # interior line can itself parse as a complete schema + # INSERT while the outer literal is still open. + out.write(line) + out.flush() + tracker.feed(line) + if line.rstrip(b"\r\n").endswith(STATEMENT_END) and ( + tracker.outside_literal or _next_line_starts_new(next_line) + ): + passthrough = False + tracker = None + elif buffered is not None: buffered.append(line) - if line.rstrip(b"\r\n").endswith(STATEMENT_END): + buffered_bytes += len(line) + if buffered_bytes > MAX_CANDIDATE_BYTES: + # Over the cap: flush what was buffered unchanged + # and stream the rest of the statement (#6525) -- + # unless the cap-crossing line itself terminates + # the candidate: then the statement is complete + # (flushed whole, unrepaired like any over-cap + # statement) and the next statement must still be + # processed normally, not streamed through. + chunk = b"".join(buffered) + for part in buffered: + out.write(part) + out.flush() + buffered = None + buffered_bytes = 0 + if not ( + line.rstrip(b"\r\n").endswith(STATEMENT_END) + and ends_statement(chunk, next_line) + ): + passthrough = True + tracker = _LiteralTracker() + tracker.feed(chunk) + elif line.rstrip(b"\r\n").endswith(STATEMENT_END): chunk = b"".join(buffered) if ends_statement(chunk, next_line): out.write(repair_chunk(chunk)) buffered = None + buffered_bytes = 0 elif line.lstrip().startswith(SCHEMA_INSERT): if line.rstrip(b"\r\n").endswith(STATEMENT_END) and ends_statement( line, next_line ): out.write(repair_chunk(line)) + elif len(line) > MAX_CANDIDATE_BYTES: + out.write(line) + passthrough = True + tracker = _LiteralTracker() + tracker.feed(line) else: buffered = [line] + buffered_bytes = len(line) else: out.write(line) line = next_line diff --git a/pkgs/cold-store-reaper/tests/test_export_turso.py b/pkgs/cold-store-reaper/tests/test_export_turso.py index bad50b309d..58bb6be651 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -313,6 +313,148 @@ def test_multiline_statement_followed_by_more_statements(self): ) self.assertEqual(self.run_filter(data), data) + def run_filter_capped(self, data: bytes, cap: int) -> bytes: + env = dict(os.environ, REPAIR_DUMP_MAX_CANDIDATE_BYTES=str(cap)) + result = subprocess.run( + [sys.executable, str(REPAIR)], + input=data, + capture_output=True, + timeout=60, + env=env, + ) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout + + def test_over_cap_candidate_streams_through_and_following_statement_is_repaired(self): + # #6525: a candidate that grows past the buffer cap without + # terminating is flushed unchanged and streamed, not held; + # its end is still recognised, so the next statement gets + # the normal repair treatment. + opener = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','big','big',0,'CREATE TABLE big (\n" + ) + filler = (b"x" * 100 + b"\n") * 100 # 10 KB, no terminator line + data = opener + filler + b"');\n" + BROKEN_SCHEMA_INSERT + expected = opener + filler + b"');\n" + ESCAPED_SCHEMA_INSERT + self.assertEqual(self.run_filter_capped(data, 4096), expected) + + def test_cap_crossed_on_terminating_line_does_not_leak_passthrough(self): + # Codex P2 on PR #8415: when the cap is first exceeded ON the + # candidate's terminating line, the statement is complete -- + # it flushes whole (unrepaired, like any over-cap statement) + # and must NOT enable pass-through, or the following statement + # streams through unrepaired even when it is below the cap + # and needs quote repair. + opener = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','big','big',0,'CREATE TABLE big (\n" + ) + filler = (b"x" * 100 + b"\n") * 39 + b"x" * 46 + b"\n" + # opener + filler stays under the 4096 cap; the terminating + # line itself is what pushes the buffer over it. + self.assertLessEqual(len(opener) + len(filler), 4096) + self.assertGreater(len(opener) + len(filler) + len(b"');\n"), 4096) + data = opener + filler + b"');\n" + BROKEN_SCHEMA_INSERT + expected = opener + filler + b"');\n" + ESCAPED_SCHEMA_INSERT + self.assertEqual(self.run_filter_capped(data, 4096), expected) + + def test_over_cap_valid_candidate_end_recognised_before_blank_line(self): + # Codex P2 on PR #8415 (second round): a correctly escaped + # candidate that crosses the cap BEFORE its terminating line + # enters pass-through; when a blank line follows the + # terminating line, ends_statement() applied to the lone + # terminating line cannot recognise the end (no statement + # head for its valid-literal path, and a blank lookahead + # fails the top-level fallback), so pass-through leaked into + # the following statement, which streamed through unrepaired. + # The pass-through literal tracker recognises the end from + # the statement's own bytes. + opener = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','big','big',0,'CREATE TABLE big (\n" + ) + filler = (b"x" * 100 + b"\n") * 100 # 10 KB, no terminator line + data = opener + filler + b"');\n" + b"\n" + BROKEN_SCHEMA_INSERT + expected = opener + filler + b"');\n" + b"\n" + ESCAPED_SCHEMA_INSERT + self.assertEqual(self.run_filter_capped(data, 4096), expected) + + def test_over_cap_interior_insert_line_is_not_a_boundary(self): + # Codex P2 on PR #8415 (third round): in pass-through mode the + # old ends_statement() fallback parsed the current interior + # line standalone -- an interior line that itself parses as a + # complete schema INSERT (the fake_complete line below, + # followed by a blank line) ended pass-through while the + # tracker was + # still inside the outer literal, and a later interior + # INSERT-prefixed line was then treated as a new repair + # candidate and quote-rewritten, corrupting the valid outer + # statement. Oracle: the whole over-cap statement is + # byte-identical and the following broken statement is + # repaired. + opener = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','big','big',0,'CREATE TABLE big (\n" + ) + filler = (b"x" * 100 + b"\n") * 50 # 5 KB: cap crossed in filler + fake_complete = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES(1,2,3,4," + b"'" * 4 + b");\n" + ) + fake_candidate = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES(1,2,3,4,''X'');\n" + ) + # The tail after fake_candidate stays below the cap, so if + # fake_candidate is wrongly taken as a new candidate its + # buffer terminates below the cap and repair_chunk runs on + # it -- that is where the corruption would appear. + filler2 = (b"x" * 100 + b"\n") * 20 + data = ( + opener + filler + fake_complete + b"\n" + fake_candidate + + filler2 + b"');\n" + BROKEN_SCHEMA_INSERT + ) + expected = ( + opener + filler + fake_complete + b"\n" + fake_candidate + + filler2 + b"');\n" + ESCAPED_SCHEMA_INSERT + ) + self.assertEqual(self.run_filter_capped(data, 4096), expected) + + def test_over_cap_candidate_emits_before_eof(self): + # #6525, the streaming half of the oracle: with stdin held + # open, output from an over-cap candidate must already be + # flowing (the old code emitted nothing until a terminator + # or EOF, buffering the whole remainder of the dump). + import select + + opener = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','big','big',0,'CREATE TABLE big (\n" + ) + filler = (b"y" * 100 + b"\n") * 100 + env = dict(os.environ, REPAIR_DUMP_MAX_CANDIDATE_BYTES="4096") + proc = subprocess.Popen( + [sys.executable, str(REPAIR)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + env=env, + ) + try: + proc.stdin.write(opener + filler) + proc.stdin.flush() + ready, _, _ = select.select([proc.stdout], [], [], 15) + self.assertTrue(ready, "no output before EOF: the candidate is being buffered whole") + first = os.read(proc.stdout.fileno(), 4096) + self.assertTrue(first.startswith(b"INSERT INTO sqlite_schema(")) + proc.stdin.write(b"');\nPRAGMA writable_schema=OFF;\n") + proc.stdin.close() + rest = proc.stdout.read() + self.assertEqual(proc.wait(timeout=60), 0) + self.assertEqual(first + rest, opener + filler + b"');\nPRAGMA writable_schema=OFF;\n") + finally: + if proc.poll() is None: + proc.kill() + if __name__ == "__main__": unittest.main() diff --git a/pkgs/cold-store-reaper/tests/test_repair_dump_property.py b/pkgs/cold-store-reaper/tests/test_repair_dump_property.py new file mode 100644 index 0000000000..e91a38732a --- /dev/null +++ b/pkgs/cold-store-reaper/tests/test_repair_dump_property.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Property-based coverage for the repair_dump streaming filter (#6525). + +Invariants (the filter contract in scripts/repair_dump.py): +- A correctly escaped sqlite_schema statement is byte-identical + after the filter, at ANY size -- in particular when it grows past + MAX_CANDIDATE_BYTES and streams through in pass-through mode + (#6525): pass-through must not rewrite, split, or lose any byte. +- The statement boundary after an over-cap correctly escaped + statement is recognised from the statement's own bytes, so the + next (below-cap, mis-escaped) statement is still repaired -- + whatever the cap position, the line splits inside the statement, + the blank lines after it, or the interior lines baiting boundary + detection (a line ending in ``');``, or a line that parses + standalone as a complete schema INSERT). + +Oracle: a sequential model of the contract. The generator emits a +dump whose expected output is known by construction: the over-cap +statement and any blank lines pass unchanged, and the one broken +statement is replaced by its escaped form. Any disagreement +between model and main() is a counterexample. (One documented +heuristic is outside the model: a candidate is taken to end where +a new top-level statement follows -- so the generator never places +a top-level-looking line directly after an interior line ending in +``');``, the ambiguous shape that heuristic exists for.) + +Stdlib-only (no hypothesis in this repo's Python tooling), like +pkgs/deploy/test_argv_property.py; a fixed seed keeps CI +deterministic, and a failing case prints its seed and case index. + +Usage: python3 -m unittest tests.test_repair_dump_property +""" + +import importlib.util +import io +import random +import sys +import unittest +from pathlib import Path + +REPAIR = Path(__file__).resolve().parent.parent / "scripts" / "repair_dump.py" + +BROKEN = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','fts','fts',0,'CREATE VIRTUAL TABLE fts" + b" USING fts5(text, content='chunks', content_rowid='id')');\n" +) +ESCAPED = BROKEN.replace(b"content='chunks'", b"content=''chunks''").replace( + b"content_rowid='id'", b"content_rowid=''id''" +) + +OPENER = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES('table','big','big',0,'CREATE TABLE big (\n" +) + +FAKE_COMPLETE = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES(1,2,3,4," + b"'" * 4 + b");" +) +FAKE_CANDIDATE = ( + b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + b" VALUES(1,2,3,4,''X'');" +) + +# Interior fragments for the over-cap statement's final literal, in +# emitted (correctly escaped) form: every quote is doubled, so each +# fragment is safe inside the literal, while several are shaped to +# bait boundary detection. +FRAGMENTS = [ + b"x", + b"col TEXT DEFAULT ''dflt'',", + b"CHECK (x <> ''),", + b"SELECT RAISE(ABORT, ''bad'');", + b"tail'');", + FAKE_COMPLETE, + FAKE_CANDIDATE, + b"-- a comment mentioning ''''); and ''quotes''", + b"", + b"y" * 137, +] + +TOP_LEVEL_PREFIXES = (b"INSERT", b"PRAGMA", b"CREATE", b"--", b"BEGIN", b"COMMIT") + + +def load_module(): + spec = importlib.util.spec_from_file_location("repair_dump_under_test", REPAIR) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def run_filter(mod, data, cap): + old_cap = mod.MAX_CANDIDATE_BYTES + old_stdin, old_stdout = sys.stdin, sys.stdout + out = io.BytesIO() + mod.MAX_CANDIDATE_BYTES = cap + sys.stdin = type("FakeStd", (), {"buffer": io.BytesIO(data)})() + sys.stdout = type("FakeStd", (), {"buffer": out})() + try: + mod.main() + finally: + sys.stdin, sys.stdout = old_stdin, old_stdout + mod.MAX_CANDIDATE_BYTES = old_cap + return out.getvalue() + + +def generate_case(rng): + lines = [] + for _ in range(rng.randint(6, 40)): + frags = [rng.choice(FRAGMENTS) for _ in range(rng.randint(1, 3))] + lines.append(b" ".join(frags) + b"\n") + # Documented-heuristic guard (see module docstring): never place + # a top-level-looking line directly after an interior line ending + # in '); . + guarded = [] + for line in lines: + if ( + guarded + and guarded[-1].rstrip(b"\r\n").endswith(b"');") + and line.lstrip().startswith(TOP_LEVEL_PREFIXES) + ): + guarded.append(b"pad pad pad\n") + guarded.append(line) + statement = OPENER + b"".join(guarded) + b"');\n" + cap = rng.choice( + [64, 128, 256, 512, 1024, 2048, rng.randint(32, len(statement) - 1)] + ) + blanks = b"\n" * rng.randint(0, 2) + tail = b"PRAGMA writable_schema=OFF;\n" if rng.random() < 0.5 else b"" + data = statement + blanks + BROKEN + tail + expected = statement + blanks + ESCAPED + tail + return data, expected, cap + + +class TestRepairDumpProperty(unittest.TestCase): + def test_over_cap_valid_statement_byte_identical_and_next_repaired(self): + mod = load_module() + rng = random.Random(6525) + for case in range(300): + data, expected, cap = generate_case(rng) + with self.subTest(case=case, cap=cap): + self.assertEqual( + run_filter(mod, data, cap), + expected, + f"seed 6525 case {case} cap {cap}", + ) + + +if __name__ == "__main__": + unittest.main() +