"""Etsy offline clone - persistent SQLite layer (stage: backend, R3). Owns the schema_migrations ledger, WAL configuration, the frozen seed corpus, and the server-side price computation. Data directory contract: CLAWBENCH_DATA_DIR (default: /data, always outside the candidate root clone/). The canonical database file is websitebench-etsy.sqlite3. Fidelity-first, decoupled from tasks: the schema and seed model generic source-site behavior (sellers/shops, listings, variation axes + per-option price data, per-combination prices and availability, per-listing personalization rules, buyer accounts, session-scoped carts, account-owned favorites). No benchmark task constant is validated for or branched on anywhere; benchmark personalization values are ordinary inputs. Duplicate-add policy (documented, applied generically): adding an identical (listing, full variation tuple, personalization) line to the same cart MERGES by summing quantities, capped by the per-listing maximum. This mirrors the source site's cart merge behavior for identical configurations. """ from __future__ import annotations import json import hashlib import os import re import sqlite3 import uuid from decimal import Decimal from pathlib import Path PACKAGE_ROOT = Path(__file__).resolve().parent CLONE_ROOT = PACKAGE_ROOT.parent SITE_ROOT = CLONE_ROOT.parent EMBEDDED = SITE_ROOT / "source-current" / "2026-07-25" / "embedded-browser" ASSET_WEB_ROOT = "/static/assets/source-current/2026-07-25" DB_FILENAME = "websitebench-etsy.sqlite3" LEGACY_DB_FILENAME = "etsy.sqlite3" FROZEN_CLOCK = "2026-07-25T12:00:00-04:00" CURRENT_LISTING_VERSION = "2026-07-25" SCHEMA_HEAD = "0007" PRICE_RE = re.compile(r"\$([0-9][0-9,]*\.[0-9]{2})") CURATION_BADGE_MARKERS = ("candidate", "task 5", "semantic match", "family") PLACEHOLDER_OPTION = "Select an option" _PAGE_FILES = { "search-personalized-wallet": "search-personalized-wallet.json", "search-dog-collar": "search-dog-collar.json", "search-blue-vase": "search-blue-vase.json", "search-bookshelf": "search-bookshelf.json", } # The four captured search queries; results are served from DB rows. SEARCH_QUERY_SEED = { "personalized leather wallet": "search-personalized-wallet", "personalized leather bifold wallet initials": "search-personalized-wallet", "custom dog collar": "search-dog-collar", "leather dog collar custom name embroidery medium sized dog": "search-dog-collar", "blue ceramic vase": "search-blue-vase", "handmade blue ceramic flower vase": "search-blue-vase", "wooden bookshelf": "search-bookshelf", "mid century modern wooden bookshelf": "search-bookshelf", } _WALLET_ID = "870439619" _COLLAR_ID = "839355276" _VASE_ID = "4526658048" _BOOKSHELF_ID = "1801448610" # Fixture-authored seller identities: the 2026-07-25 capture surfaced only a # "Made by seller" badge, never a shop name, so these synthetic shop records # are fixture-authored, not Etsy source facts. SELLERS = [ ("fixture-seller-wallet", "Fixture Leather Studio (synthetic)"), ("fixture-seller-collar", "Fixture Collar Works (synthetic)"), ("fixture-seller-vase", "Fixture Ceramics Shed (synthetic)"), ("fixture-seller-bookshelf", "Fixture Woodshop (synthetic)"), ("fixture-seller-corpus", "Fixture Marketplace Sellers (synthetic)"), ] # Synthetic local buyer accounts; never production credentials. ACCOUNTS = [ ("alex", "alex-green-fixture", "Alex Green (synthetic)"), ("jordan", "jordan-lee-fixture", "Jordan Lee (synthetic)"), ] # Fixture-authored collar size axis (the collar size axis was never directly # captured; the option list is a generic small/medium/large ladder). COLLAR_SIZE_OPTIONS = [PLACEHOLDER_OPTION, "Small", "Medium", "Large"] def data_dir() -> Path: raw = os.environ.get("WEBSITEBENCH_DATA_DIR", "").strip() return Path(raw) if raw else SITE_ROOT / "data" def db_path() -> Path: return data_dir() / DB_FILENAME def connect(path: Path | str | None = None) -> sqlite3.Connection: selected = Path(path) if path is not None else db_path() selected.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(str(selected)) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA foreign_keys=ON") conn.execute("PRAGMA busy_timeout=5000") return conn def combo_key(variations: dict[str, str]) -> str: """Canonical opaque key for a full variation tuple.""" return json.dumps( {key: variations[key] for key in sorted(variations)}, separators=(",", ":"), ensure_ascii=False, ) # --- migrations (legacy 0001-0004 preserved verbatim, head 0005) -------------- _SQL_0001_CORE_CATALOG = """ CREATE TABLE sellers ( seller_id TEXT PRIMARY KEY, shop_name TEXT NOT NULL, provenance TEXT NOT NULL DEFAULT 'fixture-authored' ); CREATE TABLE listings ( listing_id TEXT PRIMARY KEY, seller_id TEXT NOT NULL REFERENCES sellers(seller_id), family TEXT NOT NULL, task TEXT, title TEXT NOT NULL, slug TEXT NOT NULL, price_now TEXT NOT NULL, price_original TEXT, base_price_cents INTEGER, image TEXT NOT NULL, badges_json TEXT NOT NULL DEFAULT '[]', cart_enabled INTEGER NOT NULL DEFAULT 0, favorites_focused INTEGER NOT NULL DEFAULT 0, version TEXT NOT NULL, stock_state TEXT NOT NULL DEFAULT 'in-stock' ); CREATE TABLE listing_options ( listing_id TEXT NOT NULL REFERENCES listings(listing_id), axis TEXT NOT NULL, position INTEGER NOT NULL, value TEXT NOT NULL, low_cents INTEGER, high_cents INTEGER, price_tier TEXT, selectable INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (listing_id, axis, value) ); CREATE TABLE search_pages ( page_id TEXT PRIMARY KEY, title TEXT NOT NULL, cards_count INTEGER NOT NULL ); CREATE TABLE search_cards ( page_id TEXT NOT NULL REFERENCES search_pages(page_id), position INTEGER NOT NULL, listing_id TEXT NOT NULL, title TEXT NOT NULL, price_usd TEXT NOT NULL, slug TEXT NOT NULL, image TEXT NOT NULL, badges_json TEXT NOT NULL DEFAULT '[]', PRIMARY KEY (page_id, listing_id) ); CREATE TABLE accounts ( account_id TEXT PRIMARY KEY, owner_handle TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL ); """ _SQL_0002_SESSIONS_AND_CART = """ CREATE TABLE sessions ( session_id TEXT PRIMARY KEY, account_id TEXT REFERENCES accounts(account_id), created_at TEXT NOT NULL ); CREATE TABLE cart_lines ( id INTEGER PRIMARY KEY AUTOINCREMENT, owner_key TEXT NOT NULL, listing_id TEXT NOT NULL REFERENCES listings(listing_id), listing_version TEXT NOT NULL, engraving TEXT NOT NULL DEFAULT '', color TEXT NOT NULL DEFAULT '', size TEXT NOT NULL DEFAULT '', personalization TEXT NOT NULL DEFAULT '', quantity INTEGER NOT NULL, unit_price_cents INTEGER NOT NULL, created_at TEXT NOT NULL, UNIQUE (owner_key, listing_id, engraving, color, size, personalization, quantity) ); """ _SQL_0003_FAVORITES = """ CREATE TABLE favorites ( account_id TEXT NOT NULL REFERENCES accounts(account_id), listing_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (account_id, listing_id) ); """ def _migrate_0004_opaque_line_tokens(conn: sqlite3.Connection) -> None: """Cart line ids become opaque server tokens (legacy rows backfilled).""" conn.execute("ALTER TABLE cart_lines ADD COLUMN line_token TEXT") rows = conn.execute( "SELECT id FROM cart_lines WHERE line_token IS NULL" ).fetchall() for row in rows: conn.execute( "UPDATE cart_lines SET line_token = ? WHERE id = ?", (uuid.uuid4().hex, row["id"]), ) conn.execute( "CREATE UNIQUE INDEX IF NOT EXISTS idx_cart_lines_token " "ON cart_lines(line_token)" ) def _migrate_0005_generic_variation_model(conn: sqlite3.Connection) -> None: """Head migration: generic variation axes, per-combination prices and availability, per-listing personalization rules, per-listing quantity max, DB-driven search queries, and a generic cart line shape (variations_json instead of hardwired engraving/color/size columns). """ conn.executescript( """ DROP TABLE IF EXISTS listing_options; CREATE TABLE listing_axes ( listing_id TEXT NOT NULL REFERENCES listings(listing_id), position INTEGER NOT NULL, axis_label TEXT NOT NULL, PRIMARY KEY (listing_id, axis_label) ); CREATE TABLE listing_options ( listing_id TEXT NOT NULL REFERENCES listings(listing_id), axis_label TEXT NOT NULL, position INTEGER NOT NULL, value TEXT NOT NULL, delta_cents INTEGER NOT NULL DEFAULT 0, selectable INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (listing_id, axis_label, value) ); CREATE TABLE listing_combo_prices ( listing_id TEXT NOT NULL REFERENCES listings(listing_id), combo_key TEXT NOT NULL, unit_price_cents INTEGER NOT NULL, PRIMARY KEY (listing_id, combo_key) ); CREATE TABLE listing_unavailable_combos ( listing_id TEXT NOT NULL REFERENCES listings(listing_id), combo_key TEXT NOT NULL, reason TEXT NOT NULL DEFAULT 'unavailable', PRIMARY KEY (listing_id, combo_key) ); CREATE TABLE listing_personalization ( listing_id TEXT PRIMARY KEY REFERENCES listings(listing_id), enabled INTEGER NOT NULL DEFAULT 0, required INTEGER NOT NULL DEFAULT 0, char_limit INTEGER NOT NULL DEFAULT 256, prompt TEXT NOT NULL DEFAULT 'Add your personalization' ); CREATE TABLE search_queries ( query_norm TEXT PRIMARY KEY, page_id TEXT NOT NULL REFERENCES search_pages(page_id) ); ALTER TABLE listings ADD COLUMN max_quantity INTEGER NOT NULL DEFAULT 10; CREATE TABLE cart_lines_v2 ( line_token TEXT PRIMARY KEY, owner_key TEXT NOT NULL, listing_id TEXT NOT NULL REFERENCES listings(listing_id), listing_version TEXT NOT NULL, variations_json TEXT NOT NULL DEFAULT '{}', personalization TEXT NOT NULL DEFAULT '', quantity INTEGER NOT NULL, unit_price_cents INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, UNIQUE (owner_key, listing_id, variations_json, personalization) ); """ ) legacy = conn.execute( "SELECT line_token, owner_key, listing_id, listing_version, engraving," " color, size, personalization, quantity, unit_price_cents, created_at" " FROM cart_lines" ).fetchall() for row in legacy: variations: dict[str, str] = {} if row["engraving"]: variations["Engraving Options"] = row["engraving"] if row["color"]: variations["Colors"] = row["color"] if row["size"]: variations["Size"] = row["size"] conn.execute( "INSERT OR IGNORE INTO cart_lines_v2 (line_token, owner_key," " listing_id, listing_version, variations_json, personalization," " quantity, unit_price_cents, created_at, updated_at)" " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( row["line_token"] or uuid.uuid4().hex, row["owner_key"], row["listing_id"], row["listing_version"], combo_key(variations), row["personalization"], row["quantity"], row["unit_price_cents"], row["created_at"], row["created_at"], ), ) conn.executescript( """ DROP TABLE cart_lines; ALTER TABLE cart_lines_v2 RENAME TO cart_lines; """ ) def _migrate_0006_command_authority(conn: sqlite3.Connection) -> None: """Add durable command replay and optimistic-version authority. The public forms never get to choose a price, owner, aggregate, or final version. They may only present an idempotency key and an expected version; this journal lets the server atomically replay an exact retry, reject changed-payload key reuse, and serialize concurrent winners. """ conn.executescript( """ ALTER TABLE cart_lines ADD COLUMN version INTEGER NOT NULL DEFAULT 1; ALTER TABLE favorites ADD COLUMN version INTEGER NOT NULL DEFAULT 1; CREATE TABLE business_commands ( command_id TEXT PRIMARY KEY, capability TEXT NOT NULL, owner_scope TEXT NOT NULL, idempotency_key TEXT NOT NULL, payload_sha256 TEXT NOT NULL, result_json TEXT NOT NULL, created_at TEXT NOT NULL, UNIQUE (capability, owner_scope, idempotency_key) ); CREATE TABLE entity_versions ( capability TEXT NOT NULL, entity_key TEXT NOT NULL, version INTEGER NOT NULL, command_id TEXT NOT NULL REFERENCES business_commands(command_id), updated_at TEXT NOT NULL, PRIMARY KEY (capability, entity_key) ); """ ) def _migrate_0007_purchase_closure(conn: sqlite3.Connection) -> None: """Add owner-bound checkout and immutable order snapshots. The shared WebsiteBench runtime owns payment flows, attempts, and events. These site-local tables own only Etsy checkout/address/cart snapshots and the order committed when a matching shared approval is consumed. """ conn.executescript( """ CREATE TABLE checkouts ( checkout_id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id), status TEXT NOT NULL CHECK ( status IN ('pending-payment','payment-declined','payment-retry','completed','stale') ), currency TEXT NOT NULL CHECK (currency = 'USD'), item_total_cents INTEGER NOT NULL CHECK (item_total_cents >= 0), shipping_cents INTEGER NOT NULL CHECK (shipping_cents >= 0), tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0), total_cents INTEGER NOT NULL CHECK (total_cents >= 0), cart_fingerprint TEXT NOT NULL, address_json TEXT NOT NULL, payment_flow_id TEXT, version INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, UNIQUE (account_id, cart_fingerprint) ); CREATE TABLE checkout_lines ( checkout_id TEXT NOT NULL REFERENCES checkouts(checkout_id) ON DELETE RESTRICT, position INTEGER NOT NULL, cart_line_token TEXT NOT NULL, listing_id TEXT NOT NULL, listing_version TEXT NOT NULL, title TEXT NOT NULL, slug TEXT NOT NULL, image TEXT NOT NULL, variations_json TEXT NOT NULL, personalization TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0), subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0), PRIMARY KEY (checkout_id, position), UNIQUE (checkout_id, cart_line_token) ); CREATE TABLE orders ( order_id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id), checkout_id TEXT NOT NULL UNIQUE REFERENCES checkouts(checkout_id), payment_flow_id TEXT NOT NULL UNIQUE, status TEXT NOT NULL CHECK (status = 'paid'), currency TEXT NOT NULL CHECK (currency = 'USD'), item_total_cents INTEGER NOT NULL CHECK (item_total_cents >= 0), shipping_cents INTEGER NOT NULL CHECK (shipping_cents >= 0), tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0), total_cents INTEGER NOT NULL CHECK (total_cents >= 0), address_json TEXT NOT NULL, placed_at TEXT NOT NULL ); CREATE TABLE order_lines ( order_id TEXT NOT NULL REFERENCES orders(order_id) ON DELETE RESTRICT, position INTEGER NOT NULL, listing_id TEXT NOT NULL, listing_version TEXT NOT NULL, title TEXT NOT NULL, slug TEXT NOT NULL, image TEXT NOT NULL, variations_json TEXT NOT NULL, personalization TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0), subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0), PRIMARY KEY (order_id, position) ); CREATE TABLE order_events ( event_id TEXT PRIMARY KEY, order_id TEXT NOT NULL REFERENCES orders(order_id) ON DELETE RESTRICT, event_type TEXT NOT NULL CHECK (event_type = 'order-created'), snapshot_json TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE INDEX checkouts_owner_status_idx ON checkouts(account_id, status, created_at); CREATE INDEX orders_owner_placed_idx ON orders(account_id, placed_at, order_id); CREATE TRIGGER order_events_no_update BEFORE UPDATE ON order_events BEGIN SELECT RAISE(ABORT, 'order events are immutable'); END; CREATE TRIGGER order_events_no_delete BEFORE DELETE ON order_events BEGIN SELECT RAISE(ABORT, 'order events are immutable'); END; UPDATE listings SET cart_enabled = 1 WHERE stock_state = 'in-stock'; """ ) MIGRATIONS: list[tuple[str, str, object]] = [ ("0001", "core-catalog", _SQL_0001_CORE_CATALOG), ("0002", "sessions-and-cart", _SQL_0002_SESSIONS_AND_CART), ("0003", "favorites", _SQL_0003_FAVORITES), ("0004", "opaque-cart-line-tokens", _migrate_0004_opaque_line_tokens), ("0005", "generic-variation-model", _migrate_0005_generic_variation_model), ("0006", "command-authority-and-versions", _migrate_0006_command_authority), ("0007", "purchase-closure", _migrate_0007_purchase_closure), ] def migrate(conn: sqlite3.Connection, target: str | None = None) -> list[str]: """Apply pending migrations up to target (default: head). Idempotent.""" conn.execute( "CREATE TABLE IF NOT EXISTS schema_migrations (" " version TEXT PRIMARY KEY," " name TEXT NOT NULL," " applied_at TEXT NOT NULL" ")" ) applied = { row["version"] for row in conn.execute("SELECT version FROM schema_migrations") } newly_applied: list[str] = [] for version, name, action in MIGRATIONS: if target is not None and version > target: break if version in applied: continue if callable(action): action(conn) else: conn.executescript(str(action)) conn.execute( "INSERT INTO schema_migrations (version, name, applied_at) " "VALUES (?, ?, ?)", (version, name, FROZEN_CLOCK), ) newly_applied.append(version) migration_count = int( conn.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0] ) conn.execute(f"PRAGMA user_version = {migration_count}") conn.commit() return newly_applied def applied_migrations(conn: sqlite3.Connection) -> list[str]: return [ row["version"] for row in conn.execute( "SELECT version FROM schema_migrations ORDER BY version" ) ] # --- frozen seed corpus -------------------------------------------------------- def _load_capture(name: str) -> dict: return json.loads((EMBEDDED / name).read_text(encoding="utf-8")) def _slug_from_href(href: str) -> str: return href.rstrip("/").rsplit("/", 1)[-1] def _public_badges(badges: list[str]) -> list[str]: return [ badge for badge in badges if not any(marker in badge.casefold() for marker in CURATION_BADGE_MARKERS) ] def _cents(text: str) -> int: return int(Decimal(text.replace(",", "")) * 100) def _parse_range_cents(label: str) -> tuple[int, int] | None: prices = PRICE_RE.findall(label) if not prices: return None return _cents(prices[0]), _cents(prices[-1]) def _seed_search_corpus(conn: sqlite3.Connection) -> dict[str, dict]: card_index: dict[str, dict] = {} for page_id, file_name in _PAGE_FILES.items(): capture = _load_capture(file_name) conn.execute( "INSERT OR IGNORE INTO search_pages (page_id, title, cards_count) " "VALUES (?, ?, ?)", (page_id, capture["title"], capture["cards_count"]), ) for position, raw in enumerate(capture["cards"]): listing_id = raw["listing_id"] if page_id == "search-personalized-wallet" and listing_id == _WALLET_ID: image = ( f"{ASSET_WEB_ROOT}/{page_id}/" f"listing-{listing_id}-wallet-hero.jpg" ) else: image = f"{ASSET_WEB_ROOT}/{page_id}/listing-{listing_id}-card.jpg" card = { "listing_id": listing_id, "title": raw["title"], "price_usd": raw["price_usd"], "slug": _slug_from_href(raw["href"]), "image": image, "badges": _public_badges(raw.get("badges", [])), } card_index.setdefault(listing_id, card) conn.execute( "INSERT OR IGNORE INTO search_cards " "(page_id, position, listing_id, title, price_usd, slug, " " image, badges_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ( page_id, position, listing_id, card["title"], card["price_usd"], card["slug"], card["image"], json.dumps(card["badges"]), ), ) for query_norm, page_id in SEARCH_QUERY_SEED.items(): conn.execute( "INSERT OR IGNORE INTO search_queries (query_norm, page_id) " "VALUES (?, ?)", (query_norm, page_id), ) return card_index def _seed_wallet(conn: sqlite3.Connection) -> None: """Seed the wallet listing exactly from the 2026-07-25 embedded-browser structural capture: variation axes, per-option price ranges, and the derived per-combination price grid. Grid derivation (data-driven, no option-name special-cases): every engraving option label carries a captured ($low - $high) range; a color whose own captured range starts at the listing base price resolves each engraving to its low bound, any other color to its high bound. This reproduces every captured range endpoint exactly. """ capture = _load_capture("listing-personalized-wallet.json") price_now = capture["buy_box"]["price_now"] base_cents = _cents(PRICE_RE.findall(price_now)[0]) quantity_options = [] axes: list[tuple[str, list[str]]] = [] for variation in capture["variations"]: if variation["label"] == "Quantity": quantity_options = list(variation["options"]) else: axes.append((variation["label"], list(variation["options"]))) max_quantity = max(int(value) for value in quantity_options) if quantity_options else 10 conn.execute( "INSERT OR IGNORE INTO listings " "(listing_id, seller_id, family, task, title, slug, price_now, " " price_original, base_price_cents, image, badges_json, cart_enabled, " " favorites_focused, version, stock_state, max_quantity) " "VALUES (?, ?, 'wallet', '530', ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, " " 'in-stock', ?)", ( _WALLET_ID, "fixture-seller-wallet", capture["h1"], _slug_from_href(capture["final_url"]), price_now, capture["buy_box"]["price_original"], base_cents, f"{ASSET_WEB_ROOT}/search-personalized-wallet/" f"listing-{_WALLET_ID}-wallet-hero.jpg", json.dumps(list(capture["buy_box"]["badges"])), CURRENT_LISTING_VERSION, max_quantity, ), ) for axis_position, (label, options) in enumerate(axes): conn.execute( "INSERT OR IGNORE INTO listing_axes (listing_id, position, " "axis_label) VALUES (?, ?, ?)", (_WALLET_ID, axis_position, label), ) for position, option in enumerate(options): conn.execute( "INSERT OR IGNORE INTO listing_options " "(listing_id, axis_label, position, value, delta_cents, " " selectable) VALUES (?, ?, ?, ?, 0, ?)", ( _WALLET_ID, label, position, option, 0 if option == PLACEHOLDER_OPTION else 1, ), ) # Per-combination price grid from the captured per-option ranges. axis_map = dict(axes) engraving_axis = "Engraving Options" color_axis = "Colors" engraving_ranges = { option: _parse_range_cents(option) for option in axis_map[engraving_axis] if option != PLACEHOLDER_OPTION } for color in axis_map[color_axis]: if color == PLACEHOLDER_OPTION: continue color_range = _parse_range_cents(color) resolves_low = color_range is not None and color_range[0] == base_cents for engraving, engraving_range in engraving_ranges.items(): if engraving_range is None: continue unit = engraving_range[0] if resolves_low else engraving_range[1] conn.execute( "INSERT OR IGNORE INTO listing_combo_prices " "(listing_id, combo_key, unit_price_cents) VALUES (?, ?, ?)", ( _WALLET_ID, combo_key({engraving_axis: engraving, color_axis: color}), unit, ), ) # Personalization: the capture shows a '+ Add personalization' # affordance separate from the variations (optional on the source # listing). Any text within the limit is accepted verbatim. conn.execute( "INSERT OR IGNORE INTO listing_personalization " "(listing_id, enabled, required, char_limit, prompt) " "VALUES (?, 1, 0, 256, 'Add personalization (engraving text)')", (_WALLET_ID,), ) def _seed_simple_listing( conn: sqlite3.Connection, card: dict, *, seller_id: str, family: str, task: str | None, cart_enabled: int = 1, favorites_focused: int = 0, max_quantity: int = 10, ) -> None: conn.execute( "INSERT OR IGNORE INTO listings " "(listing_id, seller_id, family, task, title, slug, price_now, " " price_original, base_price_cents, image, badges_json, cart_enabled, " " favorites_focused, version, stock_state, max_quantity) " "VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 'in-stock', ?)", ( card["listing_id"], seller_id, family, task, card["title"], card["slug"], f"${card['price_usd']}", _cents(card["price_usd"]), card["image"], json.dumps(card["badges"]), cart_enabled, favorites_focused, CURRENT_LISTING_VERSION, max_quantity, ), ) def seed(conn: sqlite3.Connection, *, commit: bool = True) -> None: """Insert the frozen corpus. Idempotent (INSERT OR IGNORE keyed rows).""" for seller_id, shop_name in SELLERS: conn.execute( "INSERT OR IGNORE INTO sellers (seller_id, shop_name, provenance) " "VALUES (?, ?, 'fixture-authored')", (seller_id, shop_name), ) for account_id, owner_handle, display_name in ACCOUNTS: conn.execute( "INSERT OR IGNORE INTO accounts " "(account_id, owner_handle, display_name) VALUES (?, ?, ?)", (account_id, owner_handle, display_name), ) card_index = _seed_search_corpus(conn) _seed_wallet(conn) # Dog collar: fixture-authored Size axis + required name personalization. _seed_simple_listing( conn, card_index[_COLLAR_ID], seller_id="fixture-seller-collar", family="collar", task="531", max_quantity=10, ) conn.execute( "INSERT OR IGNORE INTO listing_axes (listing_id, position, axis_label) " "VALUES (?, 0, 'Size')", (_COLLAR_ID,), ) for position, option in enumerate(COLLAR_SIZE_OPTIONS): conn.execute( "INSERT OR IGNORE INTO listing_options " "(listing_id, axis_label, position, value, delta_cents, " " selectable) VALUES (?, 'Size', ?, ?, 0, ?)", (_COLLAR_ID, position, option, 0 if option == PLACEHOLDER_OPTION else 1), ) conn.execute( "INSERT OR IGNORE INTO listing_personalization " "(listing_id, enabled, required, char_limit, prompt) " "VALUES (?, 1, 1, 20, 'Name embroidery')", (_COLLAR_ID,), ) # Favorites-focused fixtures are still purchasable: every in-stock detail # page exposes the same cart and Buy it now contract. _seed_simple_listing( conn, card_index[_VASE_ID], seller_id="fixture-seller-vase", family="vase", task="535", cart_enabled=1, favorites_focused=1, ) _seed_simple_listing( conn, card_index[_BOOKSHELF_ID], seller_id="fixture-seller-bookshelf", family="bookshelf", task="536", cart_enabled=1, favorites_focused=1, ) # Every other captured card becomes an ordinary listing row. for listing_id, card in card_index.items(): _seed_simple_listing( conn, card, seller_id="fixture-seller-corpus", family="corpus", task=None, cart_enabled=1, ) if commit: conn.commit() def ensure_ready(path: Path | str | None = None) -> None: """Migrate to head and seed the frozen corpus if absent.""" conn = connect(path) try: migrate(conn) seed(conn) finally: conn.close() def drop_order_event_guards(conn: sqlite3.Connection) -> None: conn.execute("DROP TRIGGER IF EXISTS order_events_no_update") conn.execute("DROP TRIGGER IF EXISTS order_events_no_delete") def install_order_event_guards(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TRIGGER IF NOT EXISTS order_events_no_update BEFORE UPDATE ON order_events BEGIN SELECT RAISE(ABORT, 'order events are immutable'); END """ ) conn.execute( """ CREATE TRIGGER IF NOT EXISTS order_events_no_delete BEFORE DELETE ON order_events BEGIN SELECT RAISE(ABORT, 'order events are immutable'); END """ ) RESET_TABLE_ORDER = ( "order_events", "order_lines", "orders", "checkout_lines", "checkouts", "entity_versions", "business_commands", "favorites", "cart_lines", "sessions", "listing_unavailable_combos", "listing_combo_prices", "listing_personalization", "listing_options", "listing_axes", "search_queries", "search_cards", "search_pages", "listings", "sellers", "accounts", ) def reset(path: Path | str | None = None) -> dict: """Wipe all mutable and catalog state, then reseed the frozen corpus.""" conn = connect(path) try: migrate(conn) cleared = {} drop_order_event_guards(conn) try: for table in RESET_TABLE_ORDER: cleared[table] = conn.execute(f"DELETE FROM {table}").rowcount finally: install_order_event_guards(conn) conn.commit() seed(conn) return {"cleared": cleared, "reseeded": True} finally: conn.close() # --- server-side domain reads/writes used by the app -------------------------- def get_listing(conn: sqlite3.Connection, listing_id: str) -> sqlite3.Row | None: return conn.execute( "SELECT * FROM listings WHERE listing_id = ?", (listing_id,) ).fetchone() def listing_axes(conn: sqlite3.Connection, listing_id: str) -> list[dict]: axes = [] for axis in conn.execute( "SELECT axis_label, position FROM listing_axes WHERE listing_id = ? " "ORDER BY position", (listing_id,), ): options = conn.execute( "SELECT value, selectable FROM listing_options " "WHERE listing_id = ? AND axis_label = ? ORDER BY position", (listing_id, axis["axis_label"]), ).fetchall() axes.append( { "label": axis["axis_label"], "position": axis["position"], "field": f"variation{axis['position']}", "options": [ {"value": row["value"], "selectable": bool(row["selectable"])} for row in options ], } ) return axes def personalization_config( conn: sqlite3.Connection, listing_id: str ) -> dict: row = conn.execute( "SELECT enabled, required, char_limit, prompt " "FROM listing_personalization WHERE listing_id = ?", (listing_id,), ).fetchone() if row is None: return {"enabled": False, "required": False, "char_limit": 0, "prompt": ""} return { "enabled": bool(row["enabled"]), "required": bool(row["required"]), "char_limit": row["char_limit"], "prompt": row["prompt"], } def combo_unavailable( conn: sqlite3.Connection, listing_id: str, variations: dict[str, str] ) -> bool: row = conn.execute( "SELECT 1 FROM listing_unavailable_combos " "WHERE listing_id = ? AND combo_key = ?", (listing_id, combo_key(variations)), ).fetchone() return row is not None def unit_price_cents( conn: sqlite3.Connection, listing_id: str, variations: dict[str, str] ) -> int: """Server-authoritative unit price: per-combination grid first, else base price plus per-option deltas. Client-posted prices are never read.""" row = conn.execute( "SELECT unit_price_cents FROM listing_combo_prices " "WHERE listing_id = ? AND combo_key = ?", (listing_id, combo_key(variations)), ).fetchone() if row is not None: return row["unit_price_cents"] listing = get_listing(conn, listing_id) if listing is None: raise ValueError(f"unknown listing {listing_id}") total = listing["base_price_cents"] or 0 for axis_label, value in variations.items(): option = conn.execute( "SELECT delta_cents FROM listing_options " "WHERE listing_id = ? AND axis_label = ? AND value = ?", (listing_id, axis_label, value), ).fetchone() if option is not None: total += option["delta_cents"] return total def payload_sha256(payload: dict[str, object]) -> str: encoded = ( json.dumps( payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True, ) + "\n" ).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def prior_command( conn: sqlite3.Connection, *, capability: str, owner_scope: str, idempotency_key: str, ) -> sqlite3.Row | None: return conn.execute( "SELECT command_id, payload_sha256, result_json " "FROM business_commands WHERE capability = ? AND owner_scope = ? " "AND idempotency_key = ?", (capability, owner_scope, idempotency_key), ).fetchone() def entity_version( conn: sqlite3.Connection, *, capability: str, entity_key: str, ) -> int: row = conn.execute( "SELECT version FROM entity_versions " "WHERE capability = ? AND entity_key = ?", (capability, entity_key), ).fetchone() return int(row["version"]) if row is not None else 0 def commit_command( conn: sqlite3.Connection, *, capability: str, owner_scope: str, idempotency_key: str, payload_digest: str, result: dict[str, object], entity_key: str, next_version: int, ) -> str: command_id = uuid.uuid4().hex conn.execute( "INSERT INTO business_commands " "(command_id, capability, owner_scope, idempotency_key, " "payload_sha256, result_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", ( command_id, capability, owner_scope, idempotency_key, payload_digest, json.dumps(result, ensure_ascii=False, separators=(",", ":"), sort_keys=True), FROZEN_CLOCK, ), ) conn.execute( "INSERT INTO entity_versions " "(capability, entity_key, version, command_id, updated_at) " "VALUES (?, ?, ?, ?, ?) " "ON CONFLICT(capability, entity_key) DO UPDATE SET " "version = excluded.version, command_id = excluded.command_id, " "updated_at = excluded.updated_at", (capability, entity_key, next_version, command_id, FROZEN_CLOCK), ) return command_id