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
142 changes: 134 additions & 8 deletions pkgs/cold-store-reaper/scripts/repair_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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|--)",
Expand Down Expand Up @@ -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.

Expand All @@ -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):
Expand All @@ -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
Expand Down
142 changes: 142 additions & 0 deletions pkgs/cold-store-reaper/tests/test_export_turso.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment on lines +377 to +380

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 Add property-based coverage for the streaming parser

The new literal tracker and capped-buffer transitions introduce a parser/state machine, but the added coverage consists entirely of fixed examples. This violates AGENTS.md's explicit requirement to cover meaningful parser/state-machine invariants with property tests rather than examples alone. Add generated statements with varied escaping, line boundaries, and cap positions, asserting that over-cap statements remain byte-identical and subsequent below-cap statements are still repaired; the existing buffered parser can serve as a boundary-detection oracle for correctly escaped statements.

AGENTS.md reference: AGENTS.md:L41-L45

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8a110d6 (lane tmp-code-t, task 14417).

Added property-based coverage per the repo testing doctrine (AGENTS.md L41-45) and the pkgs/deploy precedent: pkgs/cold-store-reaper/tests/test_repair_dump_property.py is a stdlib seeded generator (no hypothesis in this repo's Python tooling; fixed seed 6525, 300 cases) that generates correctly escaped statements with varied escaping, line boundaries, interior boundary-bait lines (lines ending in ');, lines that parse standalone as complete schema INSERTs, comment lines), blank lines after the statement, and cap positions from 64 bytes to just under the statement size. The oracle is a by-construction model: the over-cap statement passes byte-identical and the following below-cap broken statement is repaired to its escaped form. The one documented heuristic outside the model (a candidate ends where a new top-level statement follows) is excluded by construction and named in the docstring.

Oracle check: 43 of the 300 generated cases fail on the pre-fix head 35aa1b7; all 300 pass now. Full cold-store-reaper suite: 162 tests OK (1 skipped).


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()
Loading
Loading