setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->exec('CREATE TABLE quote_history (id INTEGER PRIMARY KEY, dealer_id INTEGER NOT NULL, status TEXT NOT NULL, created_at TEXT NOT NULL, subtotal_cents INTEGER NOT NULL)'); $insert = $db->prepare('INSERT INTO quote_history VALUES (?, ?, ?, ?, ?)'); $db->beginTransaction(); for ($i = 1; $i <= 50000; $i++) { $insert->execute([$i, (($i * 17) % 250) + 1, ['pending','approved','converted'][($i * 7) % 3], gmdate('Y-m-d H:i:s', 1735689600 + $i * 60), 5000 + (($i * 7919) % 100000)]); } $db->commit(); $sql = 'SELECT id, subtotal_cents, created_at FROM quote_history WHERE dealer_id = ? AND status = ? ORDER BY created_at DESC LIMIT 20'; $args = [42, 'approved']; function measure(PDO $db, string $sql, array $args): array { $plan = $db->prepare('EXPLAIN QUERY PLAN '.$sql); $plan->execute($args); $query = $db->prepare($sql); for ($i=0; $i<5; $i++) { $query->execute($args); $query->fetchAll(PDO::FETCH_ASSOC); } $times = []; $rows = []; for ($i=0; $i<30; $i++) { $start=hrtime(true); $query->execute($args); $rows=$query->fetchAll(PDO::FETCH_ASSOC); $times[]=(hrtime(true)-$start)/1e6; } sort($times); return ['plan' => $plan->fetchAll(PDO::FETCH_ASSOC), 'median_ms' => round(($times[14]+$times[15])/2, 6), 'p95_ms' => round($times[28], 6), 'rows_returned' => count($rows), 'result_sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))]; } $before=measure($db,$sql,$args); $db->exec('CREATE INDEX dealer_status_recent ON quote_history(dealer_id,status,created_at)'); $db->exec('ANALYZE'); $after=measure($db,$sql,$args); if ($before['result_sha256'] !== $after['result_sha256']) throw new RuntimeException('Optimization changed result rows.'); $results = ['measured_at_utc'=>gmdate(DATE_ATOM), 'runtime'=>['php'=>PHP_VERSION,'database'=>'SQLite '.$db->query('select sqlite_version()')->fetchColumn(),'os'=>PHP_OS_FAMILY], 'dataset'=>['type'=>'synthetic','rows'=>50000,'dealers'=>250,'seed'=>'deterministic integer sequence; see tools/benchmark.php'], 'method'=>['runs'=>30,'warmups'=>5,'clock'=>'hrtime monotonic','query'=>$sql,'binds'=>$args,'index'=>'dealer_status_recent(dealer_id,status,created_at)','environment'=>'single process, in-memory database; no network, concurrent load, storage latency or production traffic'], 'before'=>$before,'after'=>$after,'mysql_status'=>'not_run: no approved isolated MySQL runtime; SQLite measurements do not establish MySQL query plans or production throughput']; $path=__DIR__.'/../../evidence/query-benchmark.json'; if (!is_dir(dirname($path))) mkdir(dirname($path),0777,true); file_put_contents($path,json_encode($results,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR).PHP_EOL); echo json_encode($results,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR).PHP_EOL;