Bookmark editor · preserve the user's next editLESSON 6.04 · 4 OF 7 IN CHAPTER
PART B / Frontend state and API integration
Step 109 of 252
LESSON 6.04 · 4 OF 7 IN CHAPTERHands-on

Bookmark editor · preserve the user's next edit

“Alice saves title A, then types B before the response arrives. Our current editor replaces B with A and says ‘Saved.’ Repair that promise across the browser, HTTP API and durable database. Which state belongs to the user, and which to the server?”

This is a constructed runnable reference vertical slice, not an AWS deployment. For an independent attempt, start with the candidate brief and keep the assessor sheet and source closed. Prerequisites: search generations, runtime boundaries, and the full-stack route.

Contract Worked behavior
Input Alice edits bookmark b, server version 1; save A, then type B
Output On success: confirmed A/v2, draft B, status “Earlier edit saved. Your newer draft is unsaved.”
Conflict Another write wins first: HTTP 409 includes current server version; B stays editable and requires explicit conflict acknowledgement
Retry Lost save acknowledgment reuses the same mutation key and exact A payload; one version increment
Pagination Order descending (created_at,id); initial tied rows b@100,a@100 then c@99
Ownership Alice cannot read or change Bob's secret; return 404 for unavailable objects
Scope Edit/search/paginate existing bookmarks; no create/delete, enrichment, multi-device offline sync, or production authentication

Draft lifetime: save responses, stale refetches, failures and conflict acknowledgment preserve the current draft. This reference keeps drafts only in memory: closing the editor, selecting another row or reloading discards unsaved text. Those are explicit scope limits, not a promise of reload/offline durability. A production editor must add a discard warning or durable draft storage before promising that navigation loses nothing.

See the editor before running it

The screenshot below is from this repository's actual local application. Alice has already saved the shorter title. She has typed a longer draft that the completed save must not erase.

Real bookmark editor showing confirmed version 2 beside a longer unsaved draft and an explicit status message.

Read Server as the last confirmed record and the Title field as current user input. The phrase “Earlier edit saved” applies to the shorter title. The extra words remain unsaved. You will follow the exact state and HTTP operations responsible for this result below.

The preceding pending state looks like this. The screenshot holds the real save response after the database write so the newer typing can happen before the browser receives confirmation:

The title input retains a newer draft while the save button says Saving and the status explains that the earlier edit is still in flight.

Run locally

Python 3.10+ and Node 24+ are enough for the application. No npm dependency is required to build the browser JavaScript; the Node build strips TypeScript syntax. From the repository root:

cd curriculum/02-applications/03-frontend/labs/bookmark-editor
node build.mjs
python server.py --db bookmarks.sqlite3 --port 8765

Open http://127.0.0.1:8765. Stop with Ctrl+C; the SQLite file preserves edits across server restarts. Use a different --db path for a fresh seeded fixture. Demonstration tokens map to Alice/Bob on the loopback server; the visible Alice token is not a production authentication design. Production login/session/CSRF/TLS and mutation-key retention policy require a separate design. Owner/version checks are real server-side checks; neither the browser nor a supplied owner field controls record ownership.

python -m unittest discover -s tests -p 'test_*.py' -v
python measure.py
# Browser test dependency, if not already installed:
npm install --no-save playwright
npx playwright install chromium
node tests/browser.mjs
# Optional separate strict type check, with TypeScript installed:
tsc -p tsconfig.json

Node syntax stripping is not a TypeScript type check. Validation evidence states exactly which checks ran. The browser tests start their own loopback server and temporary real SQLite file. Fixtures pause responses at explicit promises, complete them in a chosen order, or discard an acknowledgment after its actual API commit; there are no sleep-only race assertions.

Trace the baseline, then split state by authority

The naive baseline has one title variable. It cannot tell a pending server operation from the next local revision:

Diagram: Trace the baseline, then split state by authority

Use this method on any editor: enumerate user intent, draw a two-request schedule, name who owns each state, and move the conditional write to the authority that can enforce it. Only then add optimistic feedback and retries. A strong candidate says, “An acknowledgment confirms the snapshot sent, not every edit currently in the field.”

State Authority and purpose
draft, revision Current local text and monotonically increasing local-edit count
confirmed Last accepted server record and its version
pending Exact mutation key, title snapshot, revision sent and expected server version
generation Editor lifetime; select/close invalidates prior asynchronous work
searchGeneration Search request ordering; unrelated to bookmark versions
Diagram: Trace the baseline, then split state by authority

HTML supplies named controls, a live status region and explicit focus destinations. TypeScript (download file, source below) owns view state and request generations. HTTP router (download file, source below) validates runtime JSON and resolves demonstration identity. Schema (download file, source below) defines the durable authority: primary bookmark ID, owner, positive version, bounded title, and owner/mutation-key uniqueness. A conditional SQL update and idempotency response commit in one transaction, so the same successful request can return its original response without incrementing twice. Every response, including conflicts and replays, is sent after the transaction closes.

Read the supplied code · app.ts
TypeScript · app.ts
type Bookmark = {id: string; title: string; url: string; created_at: number; version: number};
export {}; // This file is loaded as an ES module in index.html.
type Page = {items: Bookmark[]; nextCursor: string | null};
type Pending = {key: string; title: string; revision: number; expectedVersion: number; generation: number};
const get = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T;
const title = get<HTMLInputElement>('title');
const save = get<HTMLButtonElement>('save');
const status = get<HTMLParagraphElement>('edit-status');
const headers = {Authorization: 'Bearer alice-local-token'};

function bookmark(value: unknown): Bookmark {
  const x = value as Partial<Bookmark> | null;
  if (!x || typeof x.id !== 'string' || typeof x.title !== 'string' || typeof x.url !== 'string' ||
      !Number.isSafeInteger(x.version) || Number(x.version) < 1 || !Number.isSafeInteger(x.created_at)) {
    throw new Error('Invalid bookmark response');
  }
  return x as Bookmark;
}
function page(value: unknown): Page {
  const x = value as Partial<Page> | null;
  if (!x || !Array.isArray(x.items) || (x.nextCursor !== null && typeof x.nextCursor !== 'string')) {
    throw new Error('Invalid list response');
  }
  return {items: x.items.map(bookmark), nextCursor: x.nextCursor};
}

let confirmed: Bookmark | null = null;
let draft = '';
let revision = 0;
let generation = 0; // changes on select/dispose; server versions are a separate ordering
let pending: Pending | null = null;
let saving = false;
let conflict = false;
let editorController: AbortController | null = null;
let opener: HTMLButtonElement | null = null;

function paintEditor(message?: string): void {
  get('editor').hidden = confirmed === null;
  if (!confirmed) return;
  title.value = draft;
  get('confirmed').textContent = `Server: ${confirmed.title} · version ${confirmed.version}`;
  save.disabled = saving || conflict || !draft.trim() || (!pending && draft === confirmed.title);
  save.textContent = saving ? 'Saving…' : pending ? 'Retry save' : 'Save title';
  get('resolve').hidden = !conflict;
  if (message !== undefined) status.textContent = message;
}

function openEditor(row: Bookmark, source: HTMLButtonElement): void {
  editorController?.abort();
  editorController = new AbortController();
  generation++;
  confirmed = row;
  draft = row.title;
  revision = 0;
  pending = null;
  saving = false;
  conflict = false;
  opener = source;
  paintEditor('Ready to edit.');
  title.focus();
}

function closeEditor(): void {
  generation++;
  editorController?.abort();
  confirmed = null;
  pending = null;
  saving = false;
  paintEditor();
  if (opener?.isConnected) opener.focus();
  else get('search').focus();
}

title.addEventListener('input', () => {
  draft = title.value;
  revision++;
  paintEditor(conflict ? 'Conflict. Your draft is retained. Choose the server version before saving.' :
              saving ? 'Saving the earlier edit. Your newer draft is retained.' : 'Unsaved changes.');
});

get('edit-form').addEventListener('submit', async event => {
  event.preventDefault();
  if (!confirmed || saving || conflict || !draft.trim()) return;
  // Retrying an uncertain result reuses A's exact payload and key, even after B is typed.
  pending ??= {key: crypto.randomUUID(), title: draft, revision, expectedVersion: confirmed.version, generation};
  const mutation = pending;
  const id = confirmed.id;
  saving = true;
  paintEditor('Saving…');
  try {
    const response = await fetch(`/api/bookmarks/${encodeURIComponent(id)}`, {
      method: 'PATCH', signal: editorController?.signal,
      headers: {...headers, 'Content-Type': 'application/json', 'Idempotency-Key': mutation.key},
      body: JSON.stringify({title: mutation.title, expectedVersion: mutation.expectedVersion})
    });
    const body: unknown = await response.json();
    if (generation !== mutation.generation || pending?.key !== mutation.key || !confirmed) return;
    if (response.status === 409) {
      const current = bookmark((body as {current: unknown}).current);
      if (current.id !== id) throw new Error('Mismatched bookmark response');
      if (current.version >= confirmed.version) confirmed = current;
      pending = null;
      saving = false;
      conflict = true;
      paintEditor('Conflict. Your draft is retained. Review the server copy, then keep your draft.');
      get('resolve').focus();
      return;
    }
    if (!response.ok) throw new Error(`Save failed (${response.status}).`);
    const current = bookmark(body);
    if (current.id !== id) throw new Error('Mismatched bookmark response');
    if (current.version >= confirmed.version) confirmed = current;
    if (revision === mutation.revision) draft = confirmed.title;
    pending = null;
    saving = false;
    paintEditor(draft === confirmed.title ? 'Saved.' : 'Earlier edit saved. Your newer draft is unsaved.');
  } catch (error) {
    if (generation !== mutation.generation || !confirmed) return;
    saving = false;
    paintEditor('Save outcome unavailable. Your draft is retained. Retry uses the same mutation.');
  }
});

get('resolve').addEventListener('click', () => {
  conflict = false;
  paintEditor('Draft retained. Save will use the displayed server version.');
  title.focus();
});
get('close').addEventListener('click', closeEditor);
get('refresh').addEventListener('click', async () => {
  if (!confirmed) return;
  const mine = generation, id = confirmed.id;
  try {
    const response = await fetch(`/api/bookmarks/${encodeURIComponent(id)}`, {headers, signal: editorController?.signal});
    if (!response.ok) throw new Error('Refresh failed');
    const current = bookmark(await response.json());
    if (mine !== generation || !confirmed || current.id !== id) return;
    const dirty = draft !== confirmed.title;
    if (current.version > confirmed.version) {
      confirmed = current;
      if (!dirty && !pending) draft = current.title;
      paintEditor('Server copy refreshed. Unsaved edits are retained.');
    } else {
      paintEditor('Server copy unchanged. Unsaved edits are retained.');
    }
  } catch {
    if (mine === generation && confirmed) paintEditor('Refresh failed. Your draft is retained; try Refresh again.');
  }
});

let searchGeneration = 0;
let listController: AbortController | null = null;
let nextCursor: string | null = null;
let currentQuery = '';
let rows: Bookmark[] = [];
let failedAppend = false;
async function search(append = false): Promise<void> {
  listController?.abort();
  listController = new AbortController();
  const mine = ++searchGeneration;
  if (!append) {
    currentQuery = get<HTMLInputElement>('search').value;
    // Rows and their cursor belong to one query. A failed new search must never
    // leave an old continuation usable with the new query.
    rows = [];
    nextCursor = null;
    get('results').replaceChildren();
    get('more').hidden = true;
  }
  const params = new URLSearchParams({q: currentQuery, limit: '2'});
  if (append && nextCursor) params.set('cursor', nextCursor);
  get('list-status').textContent = 'Loading…';
  get('retry-list').hidden = true;
  get<HTMLButtonElement>('more').disabled = true;
  try {
    const response = await fetch(`/api/bookmarks?${params}`, {headers, signal: listController.signal});
    if (!response.ok) throw new Error(`Search failed (${response.status})`);
    const data = page(await response.json());
    if (mine !== searchGeneration) return;
    const combined = append ? [...rows, ...data.items] : data.items;
    rows = Array.from(new Map(combined.map(row => [row.id, row])).values());
    nextCursor = data.nextCursor;
    const list = get('results');
    list.replaceChildren();
    for (const row of rows) {
      const item = document.createElement('li');
      const button = document.createElement('button');
      button.textContent = `Edit ${row.title}`;
      button.addEventListener('click', () => openEditor(row, button));
      item.append(button);
      list.append(item);
    }
    get('list-status').textContent = rows.length ? `${rows.length} bookmarks loaded.` : 'No bookmarks found.';
    get('more').hidden = nextCursor === null;
  } catch {
    if (mine !== searchGeneration) return;
    failedAppend = append;
    get('list-status').textContent = 'Search failed. Retry to load bookmarks.';
    get('retry-list').hidden = false;
  } finally {
    if (mine === searchGeneration) get<HTMLButtonElement>('more').disabled = false;
  }
}
get('search-form').addEventListener('submit', event => {event.preventDefault(); void search();});
get('more').addEventListener('click', () => {void search(true);});
get('retry-list').addEventListener('click', () => {void search(failedAppend);});
window.addEventListener('pagehide', () => {generation++; searchGeneration++; editorController?.abort(); listController?.abort();});
void search();
Read the supplied code · server.py
HTTP router · server.py
"""Loopback teaching server. Tokens below are demonstration identities, not login."""
import argparse
import base64
import binascii
from contextlib import contextmanager
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import re
import sqlite3
import unicodedata
from urllib.parse import parse_qs, urlparse

ROOT = Path(__file__).parent
TOKENS = {"Bearer alice-local-token": "alice", "Bearer bob-local-token": "bob"}


@contextmanager
def connect(path):
    db = sqlite3.connect(path, timeout=3)
    db.row_factory = sqlite3.Row
    try:
        with db:
            yield db
    finally:
        db.close()


def initialize(path):
    with connect(path) as db:
        db.executescript((ROOT / "schema.sql").read_text())
        db.executemany("INSERT OR IGNORE INTO bookmarks VALUES(?,?,?,?,?,?)", [
            ("a", "alice", "Alpha", "https://example.com/a", 100, 1),
            ("b", "alice", "Beta", "https://example.com/b", 100, 1),
            ("c", "alice", "Gamma", "https://example.com/c", 99, 1),
            ("secret", "bob", "Bob private", "https://example.com/private", 101, 1),
        ])


def record(row):
    return {k: row[k] for k in ("id", "title", "url", "created_at", "version")}


def handler(path):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *args):
            pass

        def reply(self, status, body):
            data = json.dumps(body).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            try:
                self.wfile.write(data)
            except (BrokenPipeError, ConnectionResetError):
                pass  # client disposal does not roll back an already committed mutation

        def owner(self):
            return TOKENS.get(self.headers.get("Authorization"))

        def do_GET(self):
            parsed = urlparse(self.path)
            if not parsed.path.startswith("/api/"):
                files = {"/": ("web/index.html", "text/html"),
                         "/app.js": ("web/app.js", "text/javascript"),
                         "/style.css": ("web/style.css", "text/css")}
                entry = files.get(parsed.path)
                if entry is None:
                    return self.reply(404, {"error": "not found"})
                source = ROOT / entry[0]
                if not source.exists():
                    return self.reply(503, {"error": "run node build.mjs first"})
                data = source.read_bytes()
                self.send_response(200)
                self.send_header("Content-Type", entry[1])
                self.send_header("Content-Length", str(len(data)))
                self.send_header("Content-Security-Policy", "default-src 'self'; connect-src 'self'; style-src 'self'; script-src 'self'")
                self.end_headers()
                self.wfile.write(data)
                return
            owner = self.owner()
            if owner is None:
                return self.reply(401, {"error": "local demo token required"})
            with connect(path) as db:
                if parsed.path == "/api/bookmarks":
                    params = parse_qs(parsed.query)
                    try:
                        limit = int(params.get("limit", ["2"])[0])
                        query = params.get("q", [""])[0]
                        if not 1 <= limit <= 50 or len(query) > 200:
                            raise ValueError()
                        cursor = params.get("cursor", [None])[0]
                        args = [owner, query]
                        sql = "SELECT * FROM bookmarks WHERE owner_id=? AND instr(lower(title),lower(?))>0"
                        if cursor:
                            if len(cursor) > 1000:
                                raise ValueError()
                            stamp, ident = json.loads(base64.urlsafe_b64decode(cursor.encode()))
                            if type(stamp) is not int or abs(stamp) > 2**53 - 1 or not isinstance(ident, str):
                                raise ValueError()
                            sql += " AND (created_at,id)<(?,?)"
                            args += [stamp, ident]
                        sql += " ORDER BY created_at DESC,id DESC LIMIT ?"
                        args += [limit + 1]
                        rows = db.execute(sql, args).fetchall()
                    except (ValueError, TypeError, json.JSONDecodeError, UnicodeError, binascii.Error):
                        return self.reply(400, {"error": "invalid query or cursor"})
                    page = rows[:limit]
                    next_cursor = None
                    if len(rows) > limit:
                        last = page[-1]
                        next_cursor = base64.urlsafe_b64encode(json.dumps([last["created_at"], last["id"]]).encode()).decode()
                    return self.reply(200, {"items": [record(row) for row in page], "nextCursor": next_cursor})
                ident = parsed.path.removeprefix("/api/bookmarks/")
                row = db.execute("SELECT * FROM bookmarks WHERE id=? AND owner_id=?", (ident, owner)).fetchone()
                return self.reply(200, record(row)) if row else self.reply(404, {"error": "not found"})

        def do_PATCH(self):
            owner = self.owner()
            if owner is None:
                return self.reply(401, {"error": "local demo token required"})
            if not self.path.startswith("/api/bookmarks/"):
                return self.reply(404, {"error": "not found"})
            ident = self.path.removeprefix("/api/bookmarks/")
            key = self.headers.get("Idempotency-Key", "")
            try:
                length = int(self.headers.get("Content-Length", "0"))
                if not 0 < length <= 4096 or not re.fullmatch(r"[A-Za-z0-9-]{1,80}", key):
                    raise ValueError()
                body = json.loads(self.rfile.read(length))
                if not isinstance(body, dict) or set(body) != {"title", "expectedVersion"}:
                    raise ValueError()
                title, expected = body["title"], body["expectedVersion"]
                if not isinstance(title, str) or not title.strip() or len(title) > 200 or type(expected) is not int or not 1 <= expected < 2**53 - 1:
                    raise ValueError()
                title.encode("utf-8")  # reject lone surrogates before SQLite binding
                if any(unicodedata.category(ch) == "Cc" for ch in title):
                    raise ValueError("single-line title cannot contain control characters")
            except (ValueError, TypeError, UnicodeError, json.JSONDecodeError):
                return self.reply(400, {"error": "valid single-line Unicode title, integer expectedVersion and mutation key required"})
            fingerprint = hashlib.sha256(json.dumps([ident, title, expected]).encode()).hexdigest()
            try:
                with connect(path) as db:
                    db.execute("BEGIN IMMEDIATE")
                    row = db.execute("SELECT * FROM bookmarks WHERE id=? AND owner_id=?", (ident, owner)).fetchone()
                    if row is None:
                        status, result = 404, {"error": "not found"}
                    else:
                        old = db.execute("SELECT * FROM mutations WHERE owner_id=? AND mutation_id=?", (owner, key)).fetchone()
                        if old and old["fingerprint"] != fingerprint:
                            status, result = 409, {"error": "mutation key reused with different payload", "current": record(row)}
                        elif old:
                            status, result = 200, json.loads(old["response"])
                        else:
                            changed = db.execute("UPDATE bookmarks SET title=?,version=version+1 WHERE id=? AND owner_id=? AND version=?",
                                                 (title, ident, owner, expected)).rowcount
                            if not changed:
                                status, result = 409, {"error": "version conflict", "current": record(row)}
                            else:
                                status = 200
                                result = record(db.execute("SELECT * FROM bookmarks WHERE id=? AND owner_id=?", (ident, owner)).fetchone())
                                db.execute("INSERT INTO mutations VALUES(?,?,?,?)", (owner, key, fingerprint, json.dumps(result)))
                # Every outcome is chosen under the transaction; none writes to a
                # potentially slow socket until the transaction and connection end.
                return self.reply(status, result)
            except sqlite3.OperationalError as exc:
                code = getattr(exc, "sqlite_errorcode", None)
                busy = code is not None and (code & 0xff) in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED)
                if busy or (code is None and str(exc) in ("database is locked", "database table is locked")):
                    return self.reply(503, {"error": "store busy; retry the same mutation key"})
                return self.reply(500, {"error": "store operation failed"})
    return Handler


def serve(path, port=8765):
    initialize(path)
    return ThreadingHTTPServer(("127.0.0.1", port), handler(path))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--db", default=str(ROOT / "bookmarks.sqlite3"))
    parser.add_argument("--port", type=int, default=8765)
    args = parser.parse_args()
    server = serve(args.db, args.port)
    print(f"Bookmark editor: http://127.0.0.1:{server.server_port}", flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()
Read the supplied code · schema.sql
Schema · schema.sql
PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS bookmarks (
  id TEXT PRIMARY KEY,
  owner_id TEXT NOT NULL,
  title TEXT NOT NULL CHECK(length(title) BETWEEN 1 AND 200 AND instr(title,char(0))=0),
  url TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  version INTEGER NOT NULL DEFAULT 1 CHECK(version > 0)
);
CREATE INDEX IF NOT EXISTS bookmarks_owner_created_id ON bookmarks(owner_id,created_at DESC,id DESC);
CREATE TABLE IF NOT EXISTS mutations (
  owner_id TEXT NOT NULL,
  mutation_id TEXT NOT NULL,
  fingerprint TEXT NOT NULL,
  response TEXT NOT NULL,
  PRIMARY KEY(owner_id,mutation_id)
);

Titles accept 1–200 Unicode code points, including accented text and emoji; whitespace-only titles, C0/C1 controls (including NUL/newline), and lone surrogates return structured 400 before SQL. This is not a byte or grapheme count. Unsupported input changes neither bookmarks nor replay rows. Other database faults are not all mislabeled as retryable lock contention. The schema is for fresh lab databases; existing files need an explicit migration to adopt its additional NUL constraint.

Follow-up 1 · B exists when A conflicts

Predict the field, server copy and keyboard focus after another client writes version 2 before A. Expected answer: field B remains; server copy becomes the conflict's current version; focus moves to “Keep draft and use server version.” Enter acknowledges the conflict and returns focus to the title; the next save creates a new mutation at the displayed version. A 409 is a business outcome, not a transport retry of the stale expected version. Unsaved text is never replaced merely because it has a lower version.

Diagram: Follow-up 1 · B exists when A conflicts

Follow-up 2 · old refetch, duplicate response, or disposal

An old GET at v1 arrives after save v2. Expected: it cannot lower confirmed state or overwrite an unsaved draft. A lost PATCH acknowledgment is retried with the original key and payload; duplicate success confirms the original operation once. Closing the editor invalidates its generation, aborts requests, hides the form and returns focus to its opening row. Tests also use a transport that ignores abort: cancellation saves work when honored, while generation checks protect correctness regardless.

Search has independent loading/empty/error/retry states, a generation guard, and stable tied-cursor pagination. Error and conflict flows can be completed by keyboard. The browser checks verify labels, live-region attributes and focus, not a claim of a complete screen-reader usability audit. Changing lists may remove the original opener; close then returns focus to search.

Follow-up 3 · measure before adding a cache

The measurement program (download file, source below) seeds 100,000 real SQLite rows, 90% under Alice, with ten rows per timestamp. It compares the exact same page result before and after the schema's (owner_id,created_at DESC,id DESC) index. On the recorded local run, median of 15 warm queries fell from 19.855 ms (scan plus temporary sort) to 0.030 ms (index seek). This justifies one specific improvement: the composite index. These numbers are not end-to-end latency or a production SLO. Index storage and write work increase; %substring%-style title search still examines candidate rows and may need a separate full-text search design at larger scale. No gratuitous memoization or cache is claimed as an optimization.

Read the supplied code · measure.py
measurement program · measure.py
"""Reproducible query measurement; numbers are local observations, not SLOs."""
import json
from pathlib import Path
import platform
import sqlite3
from statistics import median
import tempfile
from time import perf_counter


def measure():
    with tempfile.TemporaryDirectory() as folder:
        db = sqlite3.connect(Path(folder) / "profile.db")
        db.executescript((Path(__file__).parent / "schema.sql").read_text())
        db.execute("DROP INDEX bookmarks_owner_created_id")
        db.executemany("INSERT INTO bookmarks VALUES(?,?,?,?,?,?)", (
            (f"{i:07}", "alice" if i < 90000 else f"tenant{i % 1000}", f"Bookmark {i}", "https://example.com", i // 10, 1)
            for i in range(100000)))
        db.commit()
        sql = "SELECT id,title,version FROM bookmarks WHERE owner_id=? AND (created_at,id)<(?,?) ORDER BY created_at DESC,id DESC LIMIT 50"
        args = ("alice", 8000, "0080000")
        result = {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "rows": 100000,
                  "workload": "90% Alice; tied timestamp groups of ten; page limit 50; 15 warm queries"}
        baseline = None
        for label in ("before", "after"):
            if label == "after":
                db.execute("CREATE INDEX bookmarks_owner_created_id ON bookmarks(owner_id,created_at DESC,id DESC)")
                db.execute("ANALYZE")
            plan = [row[-1] for row in db.execute("EXPLAIN QUERY PLAN " + sql, args)]
            timings = []
            for _ in range(15):
                start = perf_counter()
                rows = db.execute(sql, args).fetchall()
                timings.append((perf_counter() - start) * 1000)
            if baseline is None:
                baseline = rows
            assert rows == baseline and len(rows) == 50
            result[label] = {"median_ms": round(median(timings), 3), "plan": plan}
        db.close()
        return result


if __name__ == "__main__":
    print(json.dumps(measure(), indent=2))

Senior evidence: independently reproduce and repair one race, explain server owner and version enforcement, and demonstrate keyboard/error recovery. Lead scope adds old/new client contract compatibility, idempotency-key retention, conflict/error metrics and rollout ownership. Complete a changed, held-back version on another day before claiming the curriculum gate. Reference tests prove reference behavior, not learner mastery.