File size: 28,523 Bytes
6a65890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
"""Site-bound SQLite lifecycle implementation."""

from __future__ import annotations

import hashlib
import json
import os
import sqlite3
import stat
import tempfile
from collections.abc import Callable, Iterator
from contextlib import closing, contextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from .errors import LifecycleError, SiteBindingError
from .runtime import RuntimeConfig


MigrationHook = Callable[[sqlite3.Connection], None]

BASE_SCHEMA = """
CREATE TABLE IF NOT EXISTS websitebench_site_binding (
    singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
    site_id TEXT NOT NULL UNIQUE,
    bound_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS websitebench_backend_migrations (
    migration_id TEXT PRIMARY KEY,
    applied_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS websitebench_mail_jobs (
    mail_id TEXT PRIMARY KEY,
    site_id TEXT NOT NULL,
    purpose TEXT NOT NULL,
    template_id TEXT NOT NULL,
    recipient TEXT NOT NULL,
    recipient_digest TEXT NOT NULL,
    variables_json TEXT NOT NULL,
    status TEXT NOT NULL CHECK (
        status IN ('LOCAL_SIMULATION','PENDING','SENT','FAILED')
    ),
    is_simulation INTEGER NOT NULL CHECK (is_simulation IN (0,1)),
    delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
    claim_token TEXT,
    claimed_at INTEGER,
    next_attempt_at INTEGER NOT NULL DEFAULT 0,
    error_category TEXT,
    sent_at TEXT,
    idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    UNIQUE (site_id, purpose, idempotency_key)
);

CREATE INDEX IF NOT EXISTS websitebench_mail_jobs_status_idx
    ON websitebench_mail_jobs(site_id, status, created_at);

CREATE TABLE IF NOT EXISTS websitebench_payment_flows (
    flow_id TEXT PRIMARY KEY,
    site_id TEXT NOT NULL,
    owner TEXT NOT NULL,
    amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
    currency TEXT NOT NULL,
    fingerprint TEXT NOT NULL,
    adapter TEXT NOT NULL,
    status TEXT NOT NULL CHECK (
        status IN ('OPEN','APPROVED','CONSUMED','INVALIDATED')
    ),
    is_simulation INTEGER NOT NULL CHECK (is_simulation = 1),
    create_idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    UNIQUE (site_id, owner, create_idempotency_key)
);

CREATE TABLE IF NOT EXISTS websitebench_payment_attempts (
    attempt_id TEXT PRIMARY KEY,
    site_id TEXT NOT NULL,
    flow_id TEXT NOT NULL
        REFERENCES websitebench_payment_flows(flow_id) ON DELETE RESTRICT,
    owner TEXT NOT NULL,
    scenario_id TEXT NOT NULL,
    amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
    currency TEXT NOT NULL,
    fingerprint TEXT NOT NULL,
    status TEXT NOT NULL CHECK (
        status IN ('APPROVED','DECLINED','RETRYABLE','SUPERSEDED','CONSUMED')
    ),
    idempotency_key TEXT NOT NULL,
    provider_reference TEXT,
    is_simulation INTEGER NOT NULL CHECK (is_simulation = 1),
    created_at TEXT NOT NULL,
    consumed_at TEXT,
    UNIQUE (site_id, flow_id, idempotency_key)
);

CREATE UNIQUE INDEX IF NOT EXISTS websitebench_payment_one_active_approval
    ON websitebench_payment_attempts(site_id, flow_id)
    WHERE status = 'APPROVED';

CREATE TABLE IF NOT EXISTS websitebench_payment_events (
    event_id TEXT PRIMARY KEY,
    site_id TEXT NOT NULL,
    flow_id TEXT NOT NULL
        REFERENCES websitebench_payment_flows(flow_id) ON DELETE RESTRICT,
    attempt_id TEXT
        REFERENCES websitebench_payment_attempts(attempt_id) ON DELETE RESTRICT,
    event_type TEXT NOT NULL,
    snapshot_json TEXT NOT NULL,
    created_at TEXT NOT NULL
);

CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_update
BEFORE UPDATE ON websitebench_payment_events
BEGIN
    SELECT RAISE(ABORT, 'payment events are immutable');
END;

CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_delete
BEFORE DELETE ON websitebench_payment_events
BEGIN
    SELECT RAISE(ABORT, 'payment events are immutable');
END;
"""


def utc_now() -> str:
    return datetime.now(UTC).isoformat().replace("+00:00", "Z")


def _is_link_or_reparse(path: Path) -> bool:
    metadata = path.lstat()
    if stat.S_ISLNK(metadata.st_mode):
        return True
    reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
    return bool(getattr(metadata, "st_file_attributes", 0) & reparse) or bool(
        hasattr(path, "is_junction") and path.is_junction()
    )


def _assert_no_existing_link(path: Path, stop: Path) -> None:
    cursor = path
    while cursor != stop:
        if cursor.exists() and _is_link_or_reparse(cursor):
            raise LifecycleError(f"database path crosses a link/reparse point: {cursor}")
        if cursor.parent == cursor:
            break
        cursor = cursor.parent
    if stop.exists() and _is_link_or_reparse(stop):
        raise LifecycleError("data root must not be a link/reparse point")


def _filesystem_root(path: Path) -> Path:
    root = Path(path.anchor)
    if not root.anchor:
        raise LifecycleError("database path must be absolute")
    return root


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _bind_hook(
    declared: str | None,
    provided: MigrationHook | None,
    *,
    label: str,
) -> MigrationHook | None:
    if declared is None:
        if provided is not None:
            raise LifecycleError(
                f"{label} callable was provided but runtime declares no {label}"
            )
        return None
    if provided is None:
        raise LifecycleError(f"runtime declares {label} {declared!r} but no callable was provided")
    actual = f"{provided.__module__}:{provided.__name__}"
    if actual != declared:
        raise LifecycleError(
            f"{label} callable {actual!r} does not match runtime declaration {declared!r}"
        )
    return provided


class SiteDatabaseLifecycle:
    """Own SQLite path safety, binding, schema, backup, restore, and health."""

    def __init__(
        self,
        runtime: RuntimeConfig,
        *,
        data_root: Path | None,
        migration_hook: MigrationHook | None,
        seed_hook: MigrationHook | None,
    ) -> None:
        self.runtime = runtime
        default_root = (
            runtime.site_root / runtime.data_dir
            if runtime.site_root is not None
            else None
        )
        if data_root is not None and default_root is not None:
            if Path(data_root).absolute() != default_root.absolute():
                raise LifecycleError(
                    "data_root cannot override a file-backed runtime contract"
                )
        selected = data_root if data_root is not None else default_root
        if selected is None:
            raise LifecycleError(
                "data_root is required when runtime config is not loaded from a file"
            )
        unresolved = Path(selected).absolute()
        filesystem_root = _filesystem_root(unresolved)
        # Check every existing component before mkdir so an intermediate
        # junction/symlink cannot redirect creation outside the declared root.
        _assert_no_existing_link(unresolved, filesystem_root)
        unresolved.mkdir(parents=True, exist_ok=True)
        if not unresolved.is_dir():
            raise LifecycleError("data_root must be a directory")
        _assert_no_existing_link(unresolved, filesystem_root)
        self.data_root = unresolved.resolve()
        self.database_path = self.data_root / runtime.database_filename
        if self.database_path.parent != self.data_root:
            raise LifecycleError("database filename escaped data_root")
        _assert_no_existing_link(self.database_path, filesystem_root)
        self._filesystem_root = filesystem_root
        self._migration_hook = _bind_hook(
            runtime.migration_hook, migration_hook, label="migration_hook"
        )
        self._seed_hook = _bind_hook(
            runtime.seed_hook, seed_hook, label="seed_hook"
        )
        self._inspect_existing_binding()

    def _connect(self, path: Path | None = None) -> sqlite3.Connection:
        selected_path = path or self.database_path
        if selected_path == self.database_path:
            _assert_no_existing_link(self.database_path, self._filesystem_root)
        connection = sqlite3.connect(
            str(selected_path), timeout=30, isolation_level=None
        )
        connection.row_factory = sqlite3.Row
        connection.execute("PRAGMA foreign_keys=ON")
        connection.execute("PRAGMA secure_delete=ON")
        connection.execute("PRAGMA busy_timeout=30000")
        return connection

    def _binding(self, connection: sqlite3.Connection) -> str | None:
        legacy = connection.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' "
            "AND name='clawbench_site_binding'"
        ).fetchone()
        if legacy is not None:
            raise SiteBindingError(
                "database is bound by the other runtime namespace; "
                "copy-only migration is required"
            )
        exists = connection.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' "
            "AND name='websitebench_site_binding'"
        ).fetchone()
        if exists is None:
            return None
        rows = connection.execute(
            "SELECT singleton,site_id FROM websitebench_site_binding"
        ).fetchall()
        if len(rows) != 1 or int(rows[0]["singleton"]) != 1:
            raise SiteBindingError("database site binding is missing or corrupt")
        return str(rows[0]["site_id"])

    def _assert_binding(self, connection: sqlite3.Connection) -> None:
        actual = self._binding(connection)
        if actual is None:
            raise SiteBindingError("database is not initialized with a site binding")
        if actual != self.runtime.site_id:
            raise SiteBindingError(
                f"database belongs to site {actual!r}, not {self.runtime.site_id!r}"
            )

    def _inspect_existing_binding(self) -> None:
        if not self.database_path.exists():
            return
        if not self.database_path.is_file() or self.database_path.is_symlink():
            raise LifecycleError("database path must be a regular file")
        try:
            with closing(self._connect()) as connection:
                actual = self._binding(connection)
        except sqlite3.DatabaseError as exc:
            raise LifecycleError(f"existing database is not valid SQLite: {exc}") from exc
        if actual is not None and actual != self.runtime.site_id:
            raise SiteBindingError(
                f"database belongs to site {actual!r}, not {self.runtime.site_id!r}"
            )
        if actual is None and not self.runtime.legacy_unbound_migration:
            raise SiteBindingError(
                "existing database has no site binding and runtime does not "
                "authorize a legacy migration"
            )

    def _integrity(self, connection: sqlite3.Connection) -> dict[str, Any]:
        integrity_rows = [
            str(row[0]) for row in connection.execute("PRAGMA integrity_check")
        ]
        foreign_keys = [
            tuple(row) for row in connection.execute("PRAGMA foreign_key_check")
        ]
        if integrity_rows != ["ok"] or foreign_keys:
            raise LifecycleError("database integrity or foreign-key check failed")
        self._assert_binding(connection)
        return {"integrity_check": "ok", "foreign_key_violations": 0}

    def _run_declared_hook_once(
        self,
        connection: sqlite3.Connection,
        *,
        kind: str,
        declaration: str | None,
        hook: MigrationHook | None,
    ) -> bool:
        if declaration is None:
            return False
        if hook is None:
            raise LifecycleError(f"{kind} hook is declared but unavailable")
        migration_id = f"site-{kind}:{declaration}"
        already_applied = connection.execute(
            "SELECT 1 FROM websitebench_backend_migrations WHERE migration_id=?",
            (migration_id,),
        ).fetchone()
        if already_applied is not None:
            return False
        hook(connection)
        connection.execute(
            "INSERT INTO websitebench_backend_migrations(migration_id,applied_at) "
            "VALUES (?,?)",
            (migration_id, utc_now()),
        )
        return True

    @staticmethod
    def _migrate_base_schema(connection: sqlite3.Connection) -> None:
        """Add v1 delivery-state columns to early site_backend databases."""

        columns = {
            str(row["name"])
            for row in connection.execute("PRAGMA table_info(websitebench_mail_jobs)")
        }
        additions = {
            "recipient": "TEXT NOT NULL DEFAULT ''",
            "claim_token": "TEXT",
            "claimed_at": "INTEGER",
            "next_attempt_at": "INTEGER NOT NULL DEFAULT 0",
            "sent_at": "TEXT",
        }
        for name, declaration in additions.items():
            if name not in columns:
                connection.execute(
                    f"ALTER TABLE websitebench_mail_jobs ADD COLUMN {name} {declaration}"
                )

    def _apply_current_runtime(
        self, connection: sqlite3.Connection, *, seed_new_database: bool
    ) -> None:
        self._run_declared_hook_once(
            connection,
            kind="migration",
            declaration=self.runtime.migration_hook,
            hook=self._migration_hook,
        )
        if seed_new_database:
            self._run_declared_hook_once(
                connection,
                kind="seed",
                declaration=self.runtime.seed_hook,
                hook=self._seed_hook,
            )
        connection.execute(
            "INSERT OR IGNORE INTO websitebench_backend_migrations"
            "(migration_id,applied_at) VALUES (?,?)",
            ("site-backend-v1", utc_now()),
        )

    def initialize(self, *, authorize_legacy_binding: bool = False) -> dict[str, Any]:
        return self._initialize(
            authorize_legacy_binding=authorize_legacy_binding,
            verify_integrity=True,
        )

    def prepare_legacy_migration(self) -> dict[str, Any]:
        """Bind/install common tables before a legacy site's repair migration.

        New scaffolds must use ``initialize``. This compatibility seam is
        available only when the frozen runtime explicitly authorizes an
        unbound legacy migration. The caller must run its site migration and
        then call ``health`` before serving traffic.
        """

        if not self.runtime.legacy_unbound_migration:
            raise LifecycleError(
                "runtime does not authorize a deferred legacy site migration"
            )
        return self._initialize(
            authorize_legacy_binding=True,
            verify_integrity=False,
        )

    def prepare_bound_site_migration(self) -> dict[str, Any]:
        """Install common tables before repairing an already bound site DB.

        This compatibility seam never adopts an unbound database. It permits
        a migrated site to repair an old business schema before the mandatory
        post-migration integrity check.
        """

        if not self.database_path.is_file() or self.database_path.stat().st_size == 0:
            raise LifecycleError(
                "bound site migration requires an existing database"
            )
        with closing(self._connect()) as connection:
            self._assert_binding(connection)
        return self._initialize(
            authorize_legacy_binding=False,
            verify_integrity=False,
        )

    def _initialize(
        self,
        *,
        authorize_legacy_binding: bool,
        verify_integrity: bool,
    ) -> dict[str, Any]:
        existed = self.database_path.exists() and self.database_path.stat().st_size > 0
        with closing(self._connect()) as connection:
            previous_binding = self._binding(connection)
            if previous_binding is None and existed:
                if not (
                    authorize_legacy_binding
                    and self.runtime.legacy_unbound_migration
                ):
                    raise SiteBindingError(
                        "legacy unbound database requires explicit migration authorization"
                    )
            elif previous_binding is not None and previous_binding != self.runtime.site_id:
                raise SiteBindingError("database belongs to another site")

            # SQLite's executescript owns its transaction edge. Install the
            # additive schema first, then bind/migrate data in one explicit
            # transaction.
            connection.executescript(BASE_SCHEMA)
            self._migrate_base_schema(connection)
            connection.execute("BEGIN IMMEDIATE")
            try:
                connection.execute(
                    "INSERT OR IGNORE INTO websitebench_site_binding"
                    "(singleton,site_id,bound_at) VALUES (1,?,?)",
                    (self.runtime.site_id, utc_now()),
                )
                self._assert_binding(connection)
                self._apply_current_runtime(
                    connection, seed_new_database=not existed
                )
                if verify_integrity:
                    self._integrity(connection)
                connection.execute("COMMIT")
            except Exception:
                if connection.in_transaction:
                    connection.execute("ROLLBACK")
                if previous_binding is None:
                    # BASE_SCHEMA is intentionally additive and may have
                    # created the singleton table before this transaction.
                    # Do not leave an empty, apparently corrupt binding behind
                    # when first-time binding/migration fails.
                    binding_rows = connection.execute(
                        "SELECT COUNT(*) FROM websitebench_site_binding"
                    ).fetchone()
                    if binding_rows is not None and int(binding_rows[0]) == 0:
                        connection.execute(
                            "DROP TABLE IF EXISTS websitebench_site_binding"
                        )
                raise
        if verify_integrity:
            return self.health()
        return {
            "status": (
                "legacy-migration-required"
                if previous_binding is None
                else "site-migration-required"
            ),
            "site_id": self.runtime.site_id,
            "database_bound": True,
        }

    @contextmanager
    def connection(self, *, transaction: bool = False) -> Iterator[sqlite3.Connection]:
        if not self.database_path.exists():
            raise LifecycleError("database is not initialized")
        connection = self._connect()
        try:
            self._assert_binding(connection)
            if transaction:
                connection.execute("BEGIN IMMEDIATE")
            yield connection
            if transaction and connection.in_transaction:
                connection.execute("COMMIT")
        except Exception:
            if transaction and connection.in_transaction:
                connection.execute("ROLLBACK")
            raise
        finally:
            connection.close()

    def reset(self, *, confirm_site_id: str) -> dict[str, Any]:
        if confirm_site_id != self.runtime.site_id:
            raise LifecycleError("reset confirmation does not match site_id")
        if self.database_path.exists():
            with closing(self._connect()) as connection:
                self._assert_binding(connection)
            for suffix in ("", "-wal", "-shm"):
                target = Path(f"{self.database_path}{suffix}")
                if target.exists():
                    if target.parent != self.data_root:
                        raise LifecycleError("reset target escaped data_root")
                    target.unlink()
        return self.initialize()

    def reset_embedded(
        self,
        connection: sqlite3.Connection,
        *,
        confirm_site_id: str,
    ) -> None:
        """Clear common mutable state inside a site's existing transaction."""

        if confirm_site_id != self.runtime.site_id:
            raise LifecycleError("embedded reset confirmation does not match site_id")
        if not connection.in_transaction:
            raise LifecycleError("embedded reset requires a caller-owned transaction")
        self._assert_binding(connection)
        connection.execute(
            "DROP TRIGGER IF EXISTS websitebench_payment_events_no_update"
        )
        connection.execute(
            "DROP TRIGGER IF EXISTS websitebench_payment_events_no_delete"
        )
        try:
            for table in (
                "websitebench_payment_events",
                "websitebench_payment_attempts",
                "websitebench_payment_flows",
                "websitebench_mail_jobs",
            ):
                connection.execute(f"DELETE FROM {table}")
        finally:
            connection.execute(
                """
                CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_update
                BEFORE UPDATE ON websitebench_payment_events
                BEGIN
                    SELECT RAISE(ABORT, 'payment events are immutable');
                END
                """
            )
            connection.execute(
                """
                CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_delete
                BEFORE DELETE ON websitebench_payment_events
                BEGIN
                    SELECT RAISE(ABORT, 'payment events are immutable');
                END
                """
            )

    def backup(self, destination: Path) -> dict[str, Any]:
        unresolved = Path(destination).absolute()
        destination_root = _filesystem_root(unresolved)
        _assert_no_existing_link(unresolved, destination_root)
        unresolved.parent.mkdir(parents=True, exist_ok=True)
        _assert_no_existing_link(unresolved, destination_root)
        parent = unresolved.parent.resolve()
        target = parent / unresolved.name
        if target == self.database_path or target.exists():
            raise LifecycleError("backup destination must be new and separate")
        if target.is_symlink():
            raise LifecycleError("backup destination must not be a link")
        with self.connection() as source:
            with closing(sqlite3.connect(str(target))) as backup:
                source.backup(backup)
                backup.row_factory = sqlite3.Row
                self._assert_binding(backup)
                integrity = self._integrity(backup)
        report = {
            "schema_version": "websitebench.site-backend-backup.v1",
            "site_id": self.runtime.site_id,
            "database": target.name,
            "bytes": target.stat().st_size,
            "sha256": _sha256(target),
            **integrity,
        }
        report_path = target.with_suffix(target.suffix + ".json")
        report_path.write_text(
            json.dumps(report, indent=2, sort_keys=True) + "\n",
            encoding="utf-8",
            newline="\n",
        )
        return {**report, "path": str(target), "report": str(report_path)}

    def restore(self, source: Path) -> dict[str, Any]:
        source_path = Path(source).absolute()
        source_root = _filesystem_root(source_path)
        if (
            not source_path.is_file()
            or source_path.is_symlink()
            or source_path.resolve() == self.database_path
        ):
            raise LifecycleError("restore source must be a separate regular file")
        _assert_no_existing_link(source_path, source_root)
        with closing(self._connect(source_path.resolve())) as source_connection:
            self._assert_binding(source_connection)
            self._integrity(source_connection)

        fd, temporary_name = tempfile.mkstemp(
            prefix=f".{self.database_path.name}.restore-",
            dir=self.data_root,
        )
        os.close(fd)
        temporary = Path(temporary_name)
        try:
            temporary.unlink()
            with closing(self._connect(source_path.resolve())) as source_connection:
                with closing(sqlite3.connect(str(temporary))) as restored:
                    source_connection.backup(restored)
            with closing(self._connect(temporary)) as restored:
                restored.executescript(BASE_SCHEMA)
                self._migrate_base_schema(restored)
                self._assert_binding(restored)
                restored.execute("BEGIN IMMEDIATE")
                try:
                    self._apply_current_runtime(
                        restored, seed_new_database=False
                    )
                    self._integrity(restored)
                    restored.execute("COMMIT")
                except Exception:
                    if restored.in_transaction:
                        restored.execute("ROLLBACK")
                    raise
            if self.database_path.exists():
                # A restored main file must never inherit pages from the
                # previous database's WAL. Switching to DELETE also fails if
                # another process still has the database actively locked.
                with closing(self._connect()) as current:
                    journal_mode = str(
                        current.execute("PRAGMA journal_mode").fetchone()[0]
                    ).casefold()
                    if journal_mode == "wal":
                        checkpoint = current.execute(
                            "PRAGMA wal_checkpoint(TRUNCATE)"
                        ).fetchone()
                        if checkpoint is None or int(checkpoint[0]) != 0:
                            raise LifecycleError(
                                "database is busy; restore cannot checkpoint WAL"
                            )
                        selected_mode = str(
                            current.execute("PRAGMA journal_mode=DELETE").fetchone()[0]
                        ).casefold()
                        if selected_mode != "delete":
                            raise LifecycleError(
                                "database is busy; restore cannot leave WAL mode"
                            )
                for suffix in ("-wal", "-shm"):
                    sidecar = Path(f"{self.database_path}{suffix}")
                    if sidecar.exists():
                        sidecar.unlink()
            os.replace(temporary, self.database_path)
        finally:
            temporary.unlink(missing_ok=True)
        return self.health()

    def health(self) -> dict[str, Any]:
        if not self.database_path.exists():
            return {
                "status": "uninitialized",
                "site_id": self.runtime.site_id,
                "database_bound": False,
            }
        with closing(self._connect()) as connection:
            binding = self._binding(connection)
            if binding is None:
                return {
                    "status": "legacy-unbound",
                    "site_id": self.runtime.site_id,
                    "database_bound": False,
                }
            self._assert_binding(connection)
            integrity = self._integrity(connection)
            counts = {}
            for name in (
                "websitebench_mail_jobs",
                "websitebench_payment_flows",
                "websitebench_payment_attempts",
                "websitebench_payment_events",
            ):
                exists = connection.execute(
                    "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
                    (name,),
                ).fetchone()
                counts[name] = (
                    int(connection.execute(f"SELECT COUNT(*) FROM {name}").fetchone()[0])
                    if exists
                    else 0
                )
        return {
            "status": "ok",
            "site_id": self.runtime.site_id,
            "database_bound": True,
            **integrity,
            "counts": counts,
        }