"""Copy-only Amazon cutover into a distinct WebsiteBench database path.""" from __future__ import annotations import sqlite3 from collections.abc import Callable from contextlib import closing from pathlib import Path from websitebench.site_backend.copy_cutover import ( CopyCutoverError, publish_transformed_sqlite_copy, ) from websitebench.site_backend.database import BASE_SCHEMA, utc_now LEGACY_FILENAME = "amazon.sqlite3" CANONICAL_FILENAME = "amazon.sqlite3" NAMESPACE_BACKUP_SUFFIX = ".clawbench-legacy" UNBOUND_BACKUP_SUFFIX = ".amazon-unbound-legacy" LEGACY_TABLES = { "clawbench_site_binding": "websitebench_site_binding", "clawbench_backend_migrations": "websitebench_backend_migrations", "clawbench_mail_jobs": "websitebench_mail_jobs", "clawbench_payment_flows": "websitebench_payment_flows", "clawbench_payment_attempts": "websitebench_payment_attempts", "clawbench_payment_events": "websitebench_payment_events", } MIGRATION_ID = "namespace-copy-v1:clawbench-to-websitebench" class NamespaceMigrationError(CopyCutoverError): """Raised when a legacy database cannot be migrated without ambiguity.""" def _objects(connection: sqlite3.Connection, kind: str) -> set[str]: return { str(row[0]) for row in connection.execute( "SELECT name FROM sqlite_master WHERE type=?", (kind,), ) } def _validate_amazon_business_schema(connection: sqlite3.Connection) -> None: required_columns = { "meta": {"key", "value"}, "catalog_products": { "asin", "slug", "title", "price_minor", "currency", }, "accounts": { "account_id", "email_normalized", "password_salt", "password_hash", }, "browser_sessions": {"session_digest", "reset_epoch", "created_at"}, } tables = _objects(connection, "table") for table, expected in required_columns.items(): if table not in tables: raise NamespaceMigrationError( "legacy database does not match the Amazon schema" ) actual = { str(row[1]) for row in connection.execute(f'PRAGMA table_info("{table}")') } if not expected.issubset(actual): raise NamespaceMigrationError( "legacy database does not match the Amazon schema" ) def _legacy_binding(connection: sqlite3.Connection) -> str | None: if "clawbench_site_binding" not in _objects(connection, "table"): return None rows = connection.execute( "SELECT singleton,site_id FROM clawbench_site_binding" ).fetchall() if len(rows) != 1 or int(rows[0][0]) != 1: raise NamespaceMigrationError("legacy site binding is missing or corrupt") return str(rows[0][1]) def _validate_canonical(database: Path, *, expected_site_id: str) -> None: try: with closing(sqlite3.connect(database)) as connection: _validate_amazon_business_schema(connection) tables = _objects(connection, "table") binding = connection.execute( "SELECT singleton,site_id FROM websitebench_site_binding" ).fetchall() integrity = connection.execute("PRAGMA integrity_check").fetchall() foreign_keys = connection.execute("PRAGMA foreign_key_check").fetchall() except sqlite3.DatabaseError as exc: raise NamespaceMigrationError( "authorized Amazon copy is not valid SQLite" ) from exc if ( binding != [(1, expected_site_id)] or integrity != [("ok",)] or foreign_keys or set(LEGACY_TABLES) & tables ): raise NamespaceMigrationError("authorized Amazon copy failed validation") def _publish( source: Path, canonical: Path, *, expected_site_id: str, transform: Callable[[Path], None], validate_source: Callable[[sqlite3.Connection], None], publication_hook: Callable[[], None] | None, ) -> None: try: publish_transformed_sqlite_copy( source, canonical, expected_source_name=LEGACY_FILENAME, expected_canonical_name=CANONICAL_FILENAME, transform=transform, validate_source=validate_source, validate_canonical=lambda path: _validate_canonical( path, expected_site_id=expected_site_id ), reserved_paths=tuple( source.with_name(source.name + suffix) for suffix in (NAMESPACE_BACKUP_SUFFIX, UNBOUND_BACKUP_SUFFIX) ), publication_hook=publication_hook, ) except CopyCutoverError as exc: if isinstance(exc, NamespaceMigrationError): raise raise NamespaceMigrationError(str(exc)) from exc def migrate_amazon_source_copy( source: Path, canonical: Path, *, expected_site_id: str, authorize_unbound: bool, prepare_copy: Callable[[Path], None], publication_hook: Callable[[], None] | None = None, ) -> bool: """Validate and migrate Amazon only after raw snapshot isolation. The legacy source is never opened through SQLite. Binding detection, business provenance, and namespace selection all inspect the owned working snapshot supplied by the shared cutover helper. """ if not source.exists(): return False mode: str | None = None def validate_source(connection: sqlite3.Connection) -> None: nonlocal mode _validate_amazon_business_schema(connection) tables = _objects(connection, "table") bound_site = _legacy_binding(connection) if bound_site is None: if "websitebench_site_binding" in tables: raise NamespaceMigrationError( "legacy Amazon source is already WebsiteBench-bound" ) if not authorize_unbound: raise NamespaceMigrationError( "legacy Amazon database requires explicit site binding" ) mode = "unbound" return if bound_site != expected_site_id: raise NamespaceMigrationError( f"legacy database belongs to site {bound_site!r}, " f"not {expected_site_id!r}" ) if set(LEGACY_TABLES.values()) & tables: raise NamespaceMigrationError( "database contains mixed WebsiteBench and ClawBench backend tables" ) missing = set(LEGACY_TABLES) - tables if missing: raise NamespaceMigrationError( "legacy site-backend schema is incomplete: " + ", ".join(sorted(missing)) ) mode = "namespace" def transform(database: Path) -> None: if mode == "namespace": _migrate_namespace_copy(database, expected_site_id=expected_site_id) return if mode == "unbound": _bind_unbound_copy( database, expected_site_id=expected_site_id, prepare_copy=prepare_copy, ) return raise NamespaceMigrationError("Amazon migration mode was not validated") _publish( source, canonical, expected_site_id=expected_site_id, transform=transform, validate_source=validate_source, publication_hook=publication_hook, ) return True def _bind_unbound_copy( database: Path, *, expected_site_id: str, prepare_copy: Callable[[Path], None], ) -> None: with closing(sqlite3.connect(database, isolation_level=None)) as connection: connection.execute("PRAGMA foreign_keys=ON") connection.executescript(BASE_SCHEMA) connection.execute("BEGIN IMMEDIATE") try: connection.execute( "INSERT INTO websitebench_site_binding" "(singleton,site_id,bound_at) VALUES (1,?,?)", (expected_site_id, utc_now()), ) connection.execute( "INSERT OR IGNORE INTO websitebench_backend_migrations" "(migration_id,applied_at) VALUES (?,?)", ("site-backend-v1", utc_now()), ) connection.execute("COMMIT") except BaseException: if connection.in_transaction: connection.execute("ROLLBACK") raise prepare_copy(database) _revoke_pre_cutover_sessions(database) def _revoke_pre_cutover_sessions(database: Path) -> None: with closing(sqlite3.connect(database, isolation_level=None)) as connection: if "local_auth_sessions" in _objects(connection, "table"): connection.execute( "UPDATE local_auth_sessions " "SET revoked_at=COALESCE(" "revoked_at, CAST(strftime('%s','now') AS INTEGER))" ) def _migrate_namespace_copy(database: Path, *, expected_site_id: str) -> None: with closing(sqlite3.connect(database, isolation_level=None)) as connection: connection.execute("PRAGMA foreign_keys=ON") connection.execute("PRAGMA busy_timeout=30000") connection.execute("BEGIN IMMEDIATE") try: connection.execute( "DROP TRIGGER IF EXISTS clawbench_payment_events_no_update" ) connection.execute( "DROP TRIGGER IF EXISTS clawbench_payment_events_no_delete" ) connection.execute("DROP INDEX IF EXISTS clawbench_mail_jobs_status_idx") connection.execute( "DROP INDEX IF EXISTS clawbench_payment_one_active_approval" ) for legacy, canonical_name in LEGACY_TABLES.items(): connection.execute( f'ALTER TABLE "{legacy}" RENAME TO "{canonical_name}"' ) connection.execute( "CREATE INDEX websitebench_mail_jobs_status_idx " "ON websitebench_mail_jobs(site_id,status,created_at)" ) connection.execute( "CREATE UNIQUE INDEX websitebench_payment_one_active_approval " "ON websitebench_payment_attempts(site_id,flow_id) " "WHERE status='APPROVED'" ) connection.execute( """ CREATE TRIGGER websitebench_payment_events_no_update BEFORE UPDATE ON websitebench_payment_events BEGIN SELECT RAISE(ABORT, 'payment events are immutable'); END """ ) connection.execute( """ CREATE TRIGGER websitebench_payment_events_no_delete BEFORE DELETE ON websitebench_payment_events BEGIN SELECT RAISE(ABORT, 'payment events are immutable'); END """ ) connection.execute( "INSERT OR IGNORE INTO websitebench_backend_migrations" "(migration_id,applied_at) VALUES (?,datetime('now'))", (MIGRATION_ID,), ) if "local_auth_sessions" in _objects(connection, "table"): connection.execute( "UPDATE local_auth_sessions " "SET revoked_at=COALESCE(" "revoked_at, CAST(strftime('%s','now') AS INTEGER))" ) connection.execute("COMMIT") except BaseException: if connection.in_transaction: connection.execute("ROLLBACK") raise