File size: 11,789 Bytes
584ed90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
"""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