From 0fcd1e3a37557850aa9fbb52b44b5423b99266f7 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 20:02:04 -0600 Subject: [PATCH 1/4] fix(cold-store-reaper): bound repair_dump candidate buffer, flush over-cap statements through (#6525) A candidate INSERT INTO sqlite_schema statement whose terminating line never arrives was buffered whole, so the documented constant-memory filter grew to the size of the remaining dump and emitted nothing until EOF. A candidate is now capped at MAX_CANDIDATE_BYTES (8 MiB default, REPAIR_DUMP_MAX_CANDIDATE_BYTES override). Past the cap the buffered lines are flushed unchanged and the rest of the statement streams through line by line with an explicit flush per line (stdout block buffering alone would hold it back); the statement end is still recognised, so the following statement is processed normally. An over-cap statement is not repaired - repair requires holding it - which matches the filter existing pass-through of anything it cannot verify. Tests: over-cap candidate streams byte-identical and the following broken statement is still repaired; over-cap candidate emits output before EOF with stdin held open. Full cold-store-reaper suite: 158 tests OK. --- pkgs/cold-store-reaper/scripts/repair_dump.py | 61 ++++++++++++++++++- .../tests/test_export_turso.py | 61 +++++++++++++++++++ 2 files changed, 120 insertions(+), 2 deletions(-) diff --git a/pkgs/cold-store-reaper/scripts/repair_dump.py b/pkgs/cold-store-reaper/scripts/repair_dump.py index eef3dfeb2f..1de5caf981 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|--)", @@ -196,24 +225,52 @@ def _final_literal_start(text): def main(): out = sys.stdout.buffer buffered = None + buffered_bytes = 0 + passthrough = False 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 (the same + # boundary test, applied to the current line), so the + # statement after it is processed normally. + out.write(line) + out.flush() + if line.rstrip(b"\r\n").endswith(STATEMENT_END) and ends_statement( + line, next_line + ): + passthrough = False + 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). + for part in buffered: + out.write(part) + out.flush() + buffered = None + buffered_bytes = 0 + passthrough = True + 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 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..a4f804dfdd 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -313,6 +313,67 @@ 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_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() From 956bd245614f7b4a240dfc6bb975b821690c87a2 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 21:21:18 -0600 Subject: [PATCH 2/4] fix(cold-store-reaper): do not leak pass-through when the cap is crossed on the terminating line (#6525) Codex P2 on PR #8415: the over-cap flush set passthrough=True unconditionally, so when a candidate first exceeded MAX_CANDIDATE_BYTES on its own terminating line, the FOLLOWING statement streamed through unrepaired even if below the cap and in need of quote repair. The flushed chunk is now checked with the same boundary test (ends_statement) and pass-through is enabled only when the candidate has not ended. Adds test_cap_crossed_on_terminating_line_does_not_leak_passthrough (fails on the unfixed code, passes with the fix); full test_export_turso suite 18/18. --- pkgs/cold-store-reaper/scripts/repair_dump.py | 14 +++++++++++-- .../tests/test_export_turso.py | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/pkgs/cold-store-reaper/scripts/repair_dump.py b/pkgs/cold-store-reaper/scripts/repair_dump.py index 1de5caf981..fbd3cb97a7 100644 --- a/pkgs/cold-store-reaper/scripts/repair_dump.py +++ b/pkgs/cold-store-reaper/scripts/repair_dump.py @@ -247,13 +247,23 @@ def main(): 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). + # 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 - passthrough = True + if not ( + line.rstrip(b"\r\n").endswith(STATEMENT_END) + and ends_statement(chunk, next_line) + ): + passthrough = True elif line.rstrip(b"\r\n").endswith(STATEMENT_END): chunk = b"".join(buffered) if ends_statement(chunk, 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 a4f804dfdd..eebdb24832 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -339,6 +339,26 @@ def test_over_cap_candidate_streams_through_and_following_statement_is_repaired( 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_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 From 35aa1b7ee3260abe81585d32b40b175c6e0d463d Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 22:32:52 -0600 Subject: [PATCH 3/4] fix(cold-store-reaper): recognise pass-through statement end from its own bytes (#6525) Codex P2 on PR #8415 (round on 956bd24561): in pass-through mode the terminating line was tested with ends_statement() alone, whose valid-literal path needs the statement head -- a lone terminating line has none, and a blank following line fails its top-level fallback, so a correctly escaped over-cap candidate followed by a blank line never ended pass-through and the next statement streamed through unrepaired. Pass-through now feeds every streamed line to an O(1) _LiteralTracker (seeded from the flushed buffer / over-cap first line) that tracks SQL string-literal state ('' = escaped quote) and recognises the end from the statement's own bytes, OR-ed with the existing ends_statement fallback for mis-escaped candidates. Regression test test_over_cap_valid_candidate_end_recognised_before_blank_line fails on the old code and passes now; full cold-store-reaper suite 160 tests OK (1 skipped). --- pkgs/cold-store-reaper/scripts/repair_dump.py | 48 ++++++++++++++++++- .../tests/test_export_turso.py | 20 ++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/pkgs/cold-store-reaper/scripts/repair_dump.py b/pkgs/cold-store-reaper/scripts/repair_dump.py index fbd3cb97a7..0614ea0550 100644 --- a/pkgs/cold-store-reaper/scripts/repair_dump.py +++ b/pkgs/cold-store-reaper/scripts/repair_dump.py @@ -222,11 +222,49 @@ 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: @@ -238,10 +276,12 @@ def main(): # statement after it is processed normally. out.write(line) out.flush() - if line.rstrip(b"\r\n").endswith(STATEMENT_END) and ends_statement( - line, next_line + tracker.feed(line) + if line.rstrip(b"\r\n").endswith(STATEMENT_END) and ( + tracker.outside_literal or ends_statement(line, next_line) ): passthrough = False + tracker = None elif buffered is not None: buffered.append(line) buffered_bytes += len(line) @@ -264,6 +304,8 @@ def main(): 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): @@ -278,6 +320,8 @@ def main(): elif len(line) > MAX_CANDIDATE_BYTES: out.write(line) passthrough = True + tracker = _LiteralTracker() + tracker.feed(line) else: buffered = [line] buffered_bytes = len(line) diff --git a/pkgs/cold-store-reaper/tests/test_export_turso.py b/pkgs/cold-store-reaper/tests/test_export_turso.py index eebdb24832..d2504edcde 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -359,6 +359,26 @@ def test_cap_crossed_on_terminating_line_does_not_leak_passthrough(self): 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_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 From 8a110d6ae18c6c1072c364b25f1e88ca3ef87172 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 10 Nov 2026 22:51:50 -0600 Subject: [PATCH 4/4] fix(cold-store-reaper): pass-through boundary from tracker/lookahead only; add property coverage (#6525) Codex round on 35aa1b7ee3, two findings: (P2) the pass-through end test OR-ed ends_statement(), which parses the current line standalone -- an interior line that itself parses as a complete schema INSERT ended pass-through while the outer literal was still open, and a later interior INSERT-prefixed line was then repaired as a new candidate, corrupting the valid outer statement. The fallback is now restricted to its lookahead half (_next_line_starts_new, shared with ends_statement): tracker-outside-literal OR next-line-starts-new OR EOF -- never a standalone parse of the current line. Regression: test_over_cap_interior_insert_line_is_not_a_boundary (fails on 35aa, passes now). (P1) property-based coverage per the repo testing doctrine: tests/test_repair_dump_property.py, stdlib seeded generator (seed 6525, 300 cases) varying escaping, line boundaries, interior boundary-bait lines, blank lines and cap positions, with a by-construction model oracle (over-cap valid statement byte-identical + following broken statement repaired). 43 of 300 cases fail on 35aa; all pass now. Full cold-store-reaper suite: 162 tests OK (1 skipped). --- pkgs/cold-store-reaper/scripts/repair_dump.py | 35 ++-- .../tests/test_export_turso.py | 41 +++++ .../tests/test_repair_dump_property.py | 152 ++++++++++++++++++ 3 files changed, 218 insertions(+), 10 deletions(-) create mode 100644 pkgs/cold-store-reaper/tests/test_repair_dump_property.py diff --git a/pkgs/cold-store-reaper/scripts/repair_dump.py b/pkgs/cold-store-reaper/scripts/repair_dump.py index 0614ea0550..057cafd230 100644 --- a/pkgs/cold-store-reaper/scripts/repair_dump.py +++ b/pkgs/cold-store-reaper/scripts/repair_dump.py @@ -181,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. @@ -196,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): @@ -271,14 +282,18 @@ def main(): next_line = next(lines, None) if passthrough: # The rest of an over-cap candidate streams through - # unchanged; only its end is still recognised (the same - # boundary test, applied to the current line), so the - # statement after it is processed normally. + # 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 ends_statement(line, next_line) + tracker.outside_literal or _next_line_starts_new(next_line) ): passthrough = False tracker = None diff --git a/pkgs/cold-store-reaper/tests/test_export_turso.py b/pkgs/cold-store-reaper/tests/test_export_turso.py index d2504edcde..58bb6be651 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -379,6 +379,47 @@ def test_over_cap_valid_candidate_end_recognised_before_blank_line(self): 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 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() +