diff --git a/tests/lifecycle_helpers.py b/tests/lifecycle_helpers.py index 74693f6ff..03d79191b 100644 --- a/tests/lifecycle_helpers.py +++ b/tests/lifecycle_helpers.py @@ -24,6 +24,7 @@ import json import os import re +import select import shutil import subprocess import tempfile @@ -273,3 +274,27 @@ def _wait_for_server(port, timeout=15): return False +def _read_until(proc, expected, timeout=15.0): + """Read raw stdout until expected appears, without waiting for process exit.""" + assert proc.stdout is not None + expected_bytes = expected.encode() + output = bytearray() + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + remaining = deadline - time.monotonic() + ready, _, _ = select.select([proc.stdout], [], [], min(0.1, remaining)) + if not ready: + if proc.poll() is not None: + output.extend(os.read(proc.stdout.fileno(), 4096)) + break + continue + chunk = os.read(proc.stdout.fileno(), 4096) + if not chunk: + break + output.extend(chunk) + if expected_bytes in output: + return output.decode("utf-8", errors="replace") + raise AssertionError( + f"timed out waiting for {expected!r}; output so far: " + f"{output.decode('utf-8', errors='replace')!r}" + ) diff --git a/tests/test_backup_job.py b/tests/test_backup_job.py index 12fa31358..f2eaf283c 100644 --- a/tests/test_backup_job.py +++ b/tests/test_backup_job.py @@ -934,9 +934,9 @@ def test_a_tampered_data_file_fails_the_restore_before_any_item(deployment, tmp_ mismatch" or, when the flipped byte sits in the gzip trailer so the decoder's own CRC fires first, "data file : data file decode error: corrupt gzip stream does not have a matching checksum" instead. A - CREATING target answers no read whatever the job did, so the GetItem - probe below only confirms the target never became readable. The backup - itself stays AVAILABLE.""" + CREATING target answers no read whatever the job did, and + `_restore_fails` checks that the target stays CREATING until it is + removed. The backup itself stays AVAILABLE.""" d = deployment _restore_cell(d) _add_backup_settings(d, RESTORE_BACKUP_SETTINGS) @@ -949,33 +949,10 @@ def test_a_tampered_data_file_fails_the_restore_before_any_item(deployment, tmp_ last = f.read(1) f.seek(-1, os.SEEK_END) f.write(bytes([last[0] ^ 0xFF])) - target = f"{name}-r" - resp = ddb.restore_table_from_backup(TargetTableName=target, BackupArn=arn)["TableDescription"] - assert resp["TableStatus"] == "CREATING", resp - assert resp["RestoreSummary"]["SourceBackupArn"] == arn, resp - readable = [] - deadline = time.monotonic() + 120 - while time.monotonic() < deadline: - try: - got = ddb.get_item(TableName=target, Key={"pk": {"S": "p0000"}, "sk": {"N": "0"}}, ConsistentRead=True) - if "Item" in got: - readable.append(got["Item"]) - except ClientError: - pass - try: - ddb.describe_table(TableName=target) - except ClientError as e: - assert e.response["Error"]["Code"] == "ResourceNotFoundException", e.response["Error"] - break - time.sleep(0.2) - else: - raise AssertionError(f"{target} was not removed within 120 s") - assert readable == [], f"an item of the failed restore was readable: {readable[:1]}" - log = server.log_text() - failed = [line for line in log.splitlines() if "FAILED (data file data/000002.json.gz does not match the manifest" in line] - assert len(failed) == 1, log[-4000:] - assert "the target was removed" in failed[0], failed[0] - assert ddb.describe_backup(BackupArn=arn)["BackupDescription"]["BackupDetails"]["BackupStatus"] == "AVAILABLE" + _restore_fails( + server, ddb, f"{name}-r", arn, + "FAILED (data file data/000002.json.gz does not match the manifest", + ) finally: server.stop() @@ -3620,13 +3597,16 @@ def every_row() -> int: def test_a_row_that_lands_during_the_moves_sync_exits_1(deployment, tmp_path): """Beside servers (PostgreSQL): server A stays on the old root, server B runs on a new root holding a copy of the old tree and 2,000 junk - prefixes (so the move's sync lists for a while). A CreateBackup on A - passes its claim reads and is held in its CREATING insert by a trigger; - `--move-store ` then moves the old row, and the trigger lets - the insert go once the move prints that it syncs the configured store. - The job's row lands under the old root during that sync: the closing - report names it under "Rows that landed under the old root during the - move" and the command exits 1, naming the remedy.""" + prefixes. A CreateBackup on A passes its claim reads and is held in its + CREATING insert by a trigger; `--move-store ` then moves the + old row, and the trigger lets the insert go once the move prints that it + syncs the configured store. The move writes to a pipe that the test stops + reading at that line: the sync's report of the junk prefixes fills it, so + the move cannot read the other stores' rows until the job's row has + committed and the test reads again. The job's row lands under the old + root during that sync: the closing report names it under "Rows that + landed under the old root during the move" and the command exits 1, + naming the remedy.""" d = deployment if d.backend == "sqlite": pytest.skip("on SQLite the serve lock keeps every server stopped during the move") @@ -3704,33 +3684,32 @@ def create() -> None: ) == 0: assert time.monotonic() < deadline, "the CreateBackup's insert is not held" time.sleep(0.1) - out_path = str(tmp_path / "move.out") - with open(out_path, "wb") as out: - moving = subprocess.Popen( - [EXTENDDB_BINARY, "backup", "--config", d.config, "sync", "--move-store", old], - cwd=d.cwd, stdout=out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, - ) + moving = subprocess.Popen( + [EXTENDDB_BINARY, "backup", "--config", d.config, "sync", "--move-store", old], + cwd=d.cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + ) released = False try: - deadline = time.monotonic() + 120 - while moving.poll() is None: - assert time.monotonic() < deadline, open(out_path).read()[-4000:] - if not released and "syncing it." in open(out_path).read(): - _catalog(d, "INSERT INTO landed_release VALUES (1)", ()) - released = True - time.sleep(0.02) - rc = moving.wait(timeout=60) + text = lh._read_until(moving, "syncing it.", timeout=120) + _catalog(d, "INSERT INTO landed_release VALUES (1)", ()) + released = True + creating.join(timeout=60) + late = result.get("arn") + assert late is not None, result + # CreateBackup answers once its row is committed. + assert _catalog( + d, "SELECT 1 FROM backup_index WHERE backup_arn = ? AND store_root = ?", (late, old) + ) == 1, "the job's row is not under the old root" + early = moving.poll() + text += moving.communicate(timeout=120)[0].decode(errors="replace") + assert early is None, "the move did not wait on its output pipe: " + text[-4000:] + rc = moving.returncode finally: if moving.poll() is None: moving.kill() - moving.wait(timeout=10) + moving.communicate(timeout=10) if not released: _catalog(d, "INSERT INTO landed_release VALUES (1)", ()) - creating.join(timeout=60) - text = open(out_path).read() - late = result.get("arn") - assert late is not None, result - assert released, "the move's sync line was printed before it ended" assert f"Moved (each row now names the configured store):\n {moved}" in text, text[-4000:] assert "--- Rows that landed under the old root during the move:\n " + late in text, text[-4000:] assert rc == 1, text[-4000:] diff --git a/tests/test_cli_migrate_concurrency.py b/tests/test_cli_migrate_concurrency.py index 25c3bb7b0..5e2e9e5e0 100644 --- a/tests/test_cli_migrate_concurrency.py +++ b/tests/test_cli_migrate_concurrency.py @@ -20,8 +20,6 @@ from __future__ import annotations -import os -import select import signal import subprocess import time @@ -31,6 +29,7 @@ PG_ADMIN_CONN, _init_args, _pg_args, + _read_until, _run_extenddb, ) @@ -63,31 +62,6 @@ def _decode(data): return data.decode("utf-8", errors="replace") -def _read_until(proc, expected, timeout=15.0): - """Read raw stdout until expected appears, without waiting for process exit.""" - assert proc.stdout is not None - expected_bytes = expected.encode() - output = bytearray() - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - remaining = deadline - time.monotonic() - ready, _, _ = select.select([proc.stdout], [], [], min(0.1, remaining)) - if not ready: - if proc.poll() is not None: - output.extend(os.read(proc.stdout.fileno(), 4096)) - break - continue - chunk = os.read(proc.stdout.fileno(), 4096) - if not chunk: - break - output.extend(chunk) - if expected_bytes in output: - return _decode(output) - raise AssertionError( - f"timed out waiting for {expected!r}; output so far: {_decode(output)!r}" - ) - - def _lose_migration_1_in_the_data_database(data_db): """The data database without migration 1: its `gsi_pending` table and its ledger row gone, so `migrate --yes` has one body to run there."""