File size: 7,912 Bytes
aec61e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Copy-only Change cutover from the legacy backend namespace."""

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,
)


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",
}
LEGACY_FILENAME = "change.sqlite3"
CANONICAL_FILENAME = "websitebench-change.sqlite3"
BACKUP_SUFFIX = ".clawbench-legacy"
MIGRATION_ID = "namespace-copy-v1:clawbench-to-websitebench"


class NamespaceMigrationError(CopyCutoverError):
    """Raised when a legacy database cannot be migrated unambiguously."""


def _tables(connection: sqlite3.Connection) -> set[str]:
    return {
        str(row[0])
        for row in connection.execute(
            "SELECT name FROM sqlite_master WHERE type='table'"
        )
    }


def _legacy_binding_connection(connection: sqlite3.Connection) -> str | None:
    try:
        if "clawbench_site_binding" not in _tables(connection):
            return None
        rows = connection.execute(
            "SELECT singleton,site_id FROM clawbench_site_binding"
        ).fetchall()
    except sqlite3.DatabaseError as exc:
        raise NamespaceMigrationError(
            "legacy site-backend database is not valid SQLite"
        ) from exc
    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 legacy_binding(database: Path) -> str | None:
    """Read the legacy site binding without changing database bytes."""

    if not database.is_file() or database.is_symlink():
        return None
    source_uri = database.resolve().as_uri() + "?mode=ro"
    with closing(sqlite3.connect(source_uri, uri=True)) as connection:
        return _legacy_binding_connection(connection)


def migrate_legacy_namespace_copy(
    source: Path,
    canonical: Path,
    *,
    expected_site_id: str,
    publication_hook: Callable[[], None] | None = None,
) -> bool:
    """Publish a canonical copy and retain the legacy source at its path."""

    source = Path(source)
    canonical = Path(canonical)
    if not source.exists():
        return False

    def validate_source(connection: sqlite3.Connection) -> None:
        bound_site = _legacy_binding_connection(connection)
        if bound_site is None:
            raise NamespaceMigrationError("legacy source has no ClawBench site binding")
        if bound_site != expected_site_id:
            raise NamespaceMigrationError(
                f"legacy database belongs to site {bound_site!r}, "
                f"not {expected_site_id!r}"
            )

    try:
        publish_transformed_sqlite_copy(
            source,
            canonical,
            expected_source_name=LEGACY_FILENAME,
            expected_canonical_name=CANONICAL_FILENAME,
            transform=lambda path: _migrate_copy(
                path, expected_site_id=expected_site_id
            ),
            validate_source=validate_source,
            validate_canonical=lambda path: _validate_canonical(
                path, expected_site_id=expected_site_id
            ),
            reserved_paths=(source.with_name(source.name + BACKUP_SUFFIX),),
            publication_hook=publication_hook,
        )
    except CopyCutoverError as exc:
        if isinstance(exc, NamespaceMigrationError):
            raise
        raise NamespaceMigrationError(str(exc)) from exc
    return True


def _validate_canonical(database: Path, *, expected_site_id: str) -> None:
    try:
        with closing(sqlite3.connect(database)) as connection:
            tables = _tables(connection)
            rows = 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("canonical copy is not valid SQLite") from exc
    if (
        rows != [(1, expected_site_id)]
        or integrity != [("ok",)]
        or foreign_keys
        or set(LEGACY_TABLES) & tables
        or set(LEGACY_TABLES.values()) - tables
    ):
        raise NamespaceMigrationError("canonical copy failed integrity validation")


def _migrate_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")
        tables = _tables(connection)
        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))
            )

        connection.execute("BEGIN IMMEDIATE")
        try:
            for name in (
                "clawbench_payment_events_no_update",
                "clawbench_payment_events_no_delete",
            ):
                connection.execute(f'DROP TRIGGER IF EXISTS "{name}"')
            for name in (
                "clawbench_mail_jobs_status_idx",
                "clawbench_payment_one_active_approval",
            ):
                connection.execute(f'DROP INDEX IF EXISTS "{name}"')
            for legacy, canonical in LEGACY_TABLES.items():
                connection.execute(f'ALTER TABLE "{legacy}" RENAME TO "{canonical}"')
            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 _tables(connection):
                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