<?php
declare(strict_types=1);

// Two PRIVATE one-worker PHP servers, one owned bind code, concurrent HTTP.
// Review draft only: hard gate blocks all lifecycle/file/DB/HTTP actions.
$lane = (string)getenv('CDX_EM_RACE_LANE');
if (!in_array($lane, ['A', 'B', 'C'], true)
    || count($argv) !== 2 || ($argv[1] ?? '') !== '--execute'
    || (string)getenv('CDX_EM_RACE_RUN') !== 'ROOT_APPROVED_TWO_PRIVATE_WORKERS_V2'
    || (string)getenv('CDX_EM_RACE_WORKER_STAGE')
        !== 'ROOT_APPROVED_PRIVATE_WORKER_STAGE_V1'
    || (string)getenv('CDX_EM_RACE_OWNED_WRITE')
        !== 'ROOT_APPROVED_OWNED_CODE_AND_TWO_HTTP_V1'
    || !hash_equals((string)hash_file('sha256', __FILE__),
        (string)getenv('CDX_EM_RACE_RUN_SHA'))) {
    echo json_encode(['status' => 'default-deny', 'db_connected' => false,
        'workers_started' => false, 'business_http_sent' => false,
        'dml_sent' => false]), PHP_EOL;
    exit(78);
}
const TWO_WORKER_LIFECYCLE_REVIEWED = false;
if (!TWO_WORKER_LIFECYCLE_REVIEWED) {
    echo json_encode(['status' => 'review-blocked', 'db_connected' => false,
        'workers_started' => false, 'business_http_sent' => false,
        'dml_sent' => false]), PHP_EOL;
    exit(78);
}
$stage = 'preflight';
$businessHttpSent = false;
set_exception_handler(static function (Throwable $error)
    use (&$stage, &$businessHttpSent): void {
    echo json_encode(['status' => 'redacted_stop', 'stage' => $stage,
        'error_class' => get_class($error), 'code' => (string)$error->getCode(),
        'business_http_sent' => $businessHttpSent,
        'recovery' => 'keep_0700_journal_and_private_workers_no_blind_retry']), PHP_EOL;
    exit(2);
});
set_error_handler(static function (int $severity): bool {
    if (!(error_reporting() & $severity)) return false;
    throw new ErrorException('redacted warning', 0, $severity);
});
$preflight = __DIR__ . '/preflight_bind_race.php';
$router = __DIR__ . '/race_router.disabled.php';
$auditor = __DIR__ . '/audit_bind_race_zero.disabled.php';
if (!hash_equals('915131476db82d3ab5c1a22a8fc460d8980bab07785fe53a3556988861717887',
        (string)hash_file('sha256', $preflight))
    || !hash_equals('6948d53a106884f58e772cbbb2afda7e44db6bddb2b513a22c5a93cb6758f700',
        (string)hash_file('sha256', $router))
    || (string)getenv('CDX_EM_RACE_AUDIT_SHA') !== (string)hash_file('sha256', $auditor)) {
    throw new RuntimeException('Reviewed preflight/router/audit source changed');
}
putenv('CDX_EM_RACE_PREFLIGHT=BIND_RACE_SCHEMA_SELECT_ONLY_V1');
putenv('CDX_EM_RACE_PREFLIGHT_SHA=915131476db82d3ab5c1a22a8fc460d8980bab07785fe53a3556988861717887');
$outerArgv = $argv;
$argv[1] = '--preflight-only';
ob_start();
require $preflight;
$preflightText = (string)ob_get_clean();
$argv = $outerArgv;
restore_exception_handler();
$preflightResult = json_decode(trim($preflightText), true);
if (!is_array($preflightResult)
    || ($preflightResult['status'] ?? null) !== 'select_only_pass'
    || ($preflightResult['lane'] ?? null) !== $lane
    || ($preflightResult['bind_code_hash_unique'] ?? null) !== true
    || ($preflightResult['store_device_id_unique'] ?? null) !== true
    || ($preflightResult['old_owned_markers'] ?? null)
        !== ['menu' => 0, 'bind' => 0, 'device' => 0, 'log' => 0]) {
    throw new RuntimeException('Reviewed same-lane SELECT preflight failed');
}
$originalRoot = $root;
$originalPid = ['A' => 21023, 'B' => 10001, 'C' => 112175][$lane];
$workerEnv = ['PATH' => (string)getenv('PATH')];
foreach (explode("\0", (string)file_get_contents('/proc/' . $originalPid . '/environ'))
    as $entry) {
    $at = strpos($entry, '=');
    if ($at === false) continue;
    $key = substr($entry, 0, $at);
    if (strpos($key, 'POC_') === 0
        || in_array($key, ['LD_LIBRARY_PATH', 'DM_SVC_PATH'], true)) {
        $workerEnv[$key] = substr($entry, $at + 1);
    }
}
if (($workerEnv['POC_EXTERNAL_STUBS'] ?? null) !== '1'
    || ($workerEnv['POC_REAL_QUEUE'] ?? null) === '1'
    || (isset($workerEnv['POC_DIALECT'])
        && $workerEnv['POC_DIALECT'] !== $dialect)) {
    throw new RuntimeException('Private worker source environment not isolated');
}
$workerEnv['POC_DIALECT'] = $dialect;
$workerEnv['POC_REAL_QUEUE'] = '0';
$lock = fopen(sys_get_temp_dir() . '/cdx-em-race-'
    . ($lane === 'C' ? 'c' : 'dev') . '.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
    throw new RuntimeException('Same-DB race writer lock unavailable');
}
$nonce = strtolower(bin2hex(random_bytes(6)));
$marker = 'CDXEMRACE' . strtoupper($nonce);
$barrierDir = '/tmp/cdx-em-race-barrier-' . $nonce;
$workerRoots = [1 => '/tmp/cdx-em-race-' . strtolower($lane) . '-' . $nonce . '-1',
    2 => '/tmp/cdx-em-race-' . strtolower($lane) . '-' . $nonce . '-2'];
$removePrivateTree = static function (string $path) use (&$removePrivateTree): void {
    if (is_link($path) || is_file($path)) {
        if (!unlink($path)) throw new RuntimeException('Private file unlink failed');
        return;
    }
    if (!is_dir($path)) return;
    if (realpath($path) !== $path) {
        throw new RuntimeException('Private removal target resolved elsewhere');
    }
    foreach (new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS) as $item) {
        $removePrivateTree($item->getPathname());
    }
    if (!rmdir($path)) throw new RuntimeException('Private directory removal failed');
};
if ((int)disk_free_space('/tmp') < 1073741824) {
    throw new RuntimeException('Private two-root disk reserve below 1 GiB');
}
foreach (array_merge([$barrierDir], array_values($workerRoots)) as $path) {
    if (file_exists($path) || !mkdir($path, 0700) || !chmod($path, 0700)) {
        throw new RuntimeException('Private race path collision');
    }
}
$journalPath = $barrierDir . '/recovery.json';
$journal = ['lane' => $lane, 'marker' => $marker,
    'worker_roots' => $workerRoots, 'worker_pids' => [1 => 0, 2 => 0],
    'worker_ports' => [1 => 0, 2 => 0],
    'menu_id' => 0, 'code_id' => 0, 'menu_uuid' => '',
    'public_token' => '', 'code_hash' => '',
    'device_ids' => [1 => $marker . 'A', 2 => $marker . 'B'],
    'source_before' => [], 'phase' => 'private_dirs_created'];
$saveJournal = static function (array $change) use (&$journal, $journalPath): void {
    $journal = array_replace_recursive($journal, $change);
    $json = json_encode($journal, JSON_UNESCAPED_SLASHES);
    if (!is_string($json) || file_put_contents($journalPath, $json, LOCK_EX) === false
        || !chmod($journalPath, 0600)) {
        throw new RuntimeException('Private recovery journal unavailable');
    }
};
$saveJournal([]);
$processes = [];
try {
$stage = 'copy_private_source_roots';
$copyTree = static function (string $source, string $destination) use (&$copyTree): void {
    if (is_link($source)) throw new RuntimeException('Unexpected nested source symlink');
    if (!is_dir($source) || !mkdir($destination, 0700)) {
        throw new RuntimeException('Private source directory copy failed');
    }
    $items = new FilesystemIterator($source, FilesystemIterator::SKIP_DOTS);
    foreach ($items as $item) {
        $target = $destination . '/' . $item->getFilename();
        if ($item->isLink()) throw new RuntimeException('Nested source symlink unsafe');
        if ($item->isDir()) $copyTree($item->getPathname(), $target);
        elseif (!$item->isFile() || !copy($item->getPathname(), $target)) {
            throw new RuntimeException('Private source file copy failed');
        }
    }
};
foreach ($workerRoots as $privateRoot) {
    $copyTree($originalRoot . '/application', $privateRoot . '/application');
    $copyTree($originalRoot . '/public', $privateRoot . '/public');
    foreach (['env.php', 'external_stubs.php', 'think', 'version.json'] as $file) {
        if (is_file($originalRoot . '/' . $file)
            && !copy($originalRoot . '/' . $file, $privateRoot . '/' . $file)) {
            throw new RuntimeException('Private runtime file copy failed');
        }
    }
    foreach (['vendor', 'thinkphp', 'extend'] as $name) {
        $target = realpath($originalRoot . '/' . $name);
        if ($target === false || !is_dir($target)
            || !symlink($target, $privateRoot . '/' . $name)) {
            throw new RuntimeException('Reviewed library symlink unavailable');
        }
    }
    foreach (['runtime', 'runtime/cache', 'runtime/log'] as $name) {
        if (!mkdir($privateRoot . '/' . $name, 0700)) {
            throw new RuntimeException('Private cache/log root unavailable');
        }
    }
    foreach (['application/common/service/ElectronicMenuDevice.php'
            => '3335769aee94126f7abfae2f2a305ba09cca9270df2ab7590657c00fabef855f',
        'application/api/controller/ElectronicMenu.php'
            => '2c1df1125c5ced2abd4f97a460f4290950d8ca5fbb978d63800e76ba5d60e056']
        as $file => $sha) {
        if (!hash_equals($sha, (string)hash_file('sha256', $privateRoot . '/' . $file))) {
            throw new RuntimeException('Copied private source changed');
        }
    }
}
$saveJournal(['phase' => 'two_private_roots_copied']);
$stage = 'private_rendezvous_and_worker_start';
$guard = ['status' => 'prepared', 'marker' => $marker,
    'device_ids' => $journal['device_ids']];
$state = ['arrivals' => [1 => null, 2 => null],
    'released' => false, 'aborted' => false,
    'dispatch' => [1 => null, 2 => null]];
foreach (['guard.json' => $guard, 'state.json' => $state] as $name => $data) {
    $path = $barrierDir . '/' . $name;
    if (file_put_contents($path, json_encode($data, JSON_UNESCAPED_SLASHES), LOCK_EX)
            === false || !chmod($path, 0600)) {
        throw new RuntimeException('Private rendezvous state unavailable');
    }
}
$reservePort = static function (): int {
    $server = stream_socket_server('tcp://127.0.0.1:0', $errorNo, $errorText);
    if ($server === false) throw new RuntimeException('Private loopback port unavailable');
    $address = stream_socket_get_name($server, false);
    fclose($server);
    $port = (int)substr((string)$address, strrpos((string)$address, ':') + 1);
    if ($port < 1024 || $port > 65535) throw new RuntimeException('Private port invalid');
    return $port;
};
$ownsListener = static function (int $targetPid, int $targetPort): bool {
    $hex = strtoupper(str_pad(dechex($targetPort), 4, '0', STR_PAD_LEFT));
    $lines = @file('/proc/net/tcp', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!is_array($lines)) return false;
    $inodes = [];
    foreach (array_slice($lines, 1) as $line) {
        $parts = preg_split('/\s+/', trim($line));
        if (is_array($parts) && ($parts[1] ?? '') === '0100007F:' . $hex
            && ($parts[3] ?? '') === '0A') $inodes[] = (string)($parts[9] ?? '');
    }
    if (count($inodes) !== 1 || $inodes[0] === '') return false;
    $fds = glob('/proc/' . $targetPid . '/fd/*');
    if (!is_array($fds)) return false;
    foreach ($fds as $fd) {
        if (@readlink($fd) === 'socket:[' . $inodes[0] . ']') return true;
    }
    return false;
};
$ports = [1 => $reservePort(), 2 => $reservePort()];
if ($ports[1] === $ports[2]) throw new RuntimeException('Private port collision');
$php = realpath(PHP_BINARY);
if ($php === false) throw new RuntimeException('PHP binary unresolved');
foreach ([1, 2] as $side) {
    $privateRoot = $workerRoots[$side];
    $port = $ports[$side];
    $environment = $workerEnv;
    $environment['POC_APP_ROOT'] = $privateRoot;
    $environment['POC_TARGET_ROOT'] = $privateRoot;
    $environment['POC_BASE_URL'] = 'http://127.0.0.1:' . $port;
    $environment['CDX_EM_RACE_PRIVATE_ROOT'] = $privateRoot;
    $environment['CDX_EM_RACE_BARRIER_DIR'] = $barrierDir;
    $environment['CDX_EM_RACE_SIDE'] = (string)$side;
    $environment['CDX_EM_RACE_ROUTER_SHA'] =
        '6948d53a106884f58e772cbbb2afda7e44db6bddb2b513a22c5a93cb6758f700';
    unset($environment['PHP_CLI_SERVER_WORKERS']);
    $args = [escapeshellarg($php)];
    if ($lane === 'C') {
        foreach (['POC_DM_PHP_LIB', 'POC_DM_PHP_PDO'] as $key) {
            $extension = (string)($workerEnv[$key] ?? '');
            if ($extension === '' || !is_file($extension)) {
                throw new RuntimeException('Private C DM PHP extension unavailable');
            }
            $args[] = '-d';
            $args[] = escapeshellarg('extension=' . $extension);
        }
    }
    array_push($args, '-S', escapeshellarg('127.0.0.1:' . $port),
        '-t', escapeshellarg($privateRoot . '/public'), escapeshellarg($router));
    $command = 'exec ' . implode(' ', $args);
    $process = proc_open($command, [0 => ['pipe', 'r'],
        1 => ['file', $barrierDir . '/worker' . $side . '.out', 'a'],
        2 => ['file', $barrierDir . '/worker' . $side . '.err', 'a']],
        $pipes, $privateRoot, $environment);
    if (!is_resource($process)) throw new RuntimeException('Private worker start failed');
    $processes[$side] = $process;
    fclose($pipes[0]);
    $status = proc_get_status($process);
    $workerPid = (int)($status['pid'] ?? 0);
    if ($workerPid <= 0) throw new RuntimeException('Private worker PID unavailable');
    $journal['worker_pids'][$side] = $workerPid;
    $journal['worker_ports'][$side] = $port;
    $saveJournal(['worker_pids' => [$side => $workerPid],
        'worker_ports' => [$side => $port], 'phase' => 'workers_starting']);
}
$workerStatus = [];
foreach ([1, 2] as $side) {
    $url = 'http://127.0.0.1:' . $ports[$side];
    $response = false;
    for ($attempt = 0; $attempt < 25 && $response === false; $attempt++) {
        usleep(100000);
        $response = @file_get_contents($url . '/__poc_race_status', false,
            stream_context_create(['http' => ['timeout' => 1]]));
    }
    $status = is_string($response) ? json_decode($response, true) : null;
    $boundary = json_decode((string)@file_get_contents($url . '/__poc_boundary',
        false, stream_context_create(['http' => ['timeout' => 2]])), true);
    if (!is_array($status) || ($status['private_race_router'] ?? null) !== true
        || (int)($status['pid'] ?? 0) !== (int)$journal['worker_pids'][$side]
        || (int)($status['side'] ?? 0) !== $side
        || !$ownsListener((int)$journal['worker_pids'][$side], $port)
        || ($status['released'] ?? null) !== false
        || !is_array($boundary)
        || ($boundary['external_stubs'] ?? null) !== true
        || ($boundary['redis_isolated'] ?? null) !== true
        || ($boundary['real_queue'] ?? true) !== false) {
        throw new RuntimeException('Private worker boundary did not start safely');
    }
    $workerStatus[$side] = true;
}
$saveJournal(['phase' => 'two_workers_ready']);
} catch (Throwable $startupError) {
    // No fixture DML has begun. Stop only new processes, then remove only
    // this nonce's private dirs. If termination is uncertain, retain journal.
    $allStopped = true;
    foreach ($processes as $process) {
        if (!is_resource($process) || !@proc_terminate($process)) {
            $allStopped = false;
            continue;
        }
        @proc_close($process);
    }
    foreach ($journal['worker_pids'] as $workerPid) {
        if ((int)$workerPid > 0 && is_dir('/proc/' . (int)$workerPid)) {
            $allStopped = false;
        }
    }
    if ($allStopped) {
        foreach ($workerRoots as $side => $path) {
            if ($path === '/tmp/cdx-em-race-' . strtolower($lane)
                . '-' . $nonce . '-' . $side) $removePrivateTree($path);
        }
        if ($barrierDir === '/tmp/cdx-em-race-barrier-' . $nonce) {
            $removePrivateTree($barrierDir);
        }
    }
    throw $startupError;
}

// The following DB/HTTP portion is still behind TWO_WORKER_LIFECYCLE_REVIEWED.
$stage = 'owned_fixture_and_competition';
$t = static function (string $short) use ($dialect): string {
    if (!in_array($short, ['electronic_menu',
        'electronic_menu_bind_code', 'electronic_menu_device',
        'electronic_menu_device_log'], true)) {
        throw new RuntimeException('Unapproved table');
    }
    return $dialect === 'dm' ? strtoupper('ydy_' . $short) : 'ydy_' . $short;
};
$connect = static function () use ($dsn, $config, $dialect): PDO {
    $user = $dialect === 'dm' ? (string)getenv('POC_USER')
        : (string)$config['username'];
    $password = $dialect === 'dm' ? (string)getenv('POC_PASSWORD')
        : (string)$config['password'];
    return new PDO($dsn, $user, $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
};
$sourceBefore = [];
foreach (['electronic_menu', 'electronic_menu_bind_code',
    'electronic_menu_device', 'electronic_menu_device_log'] as $short) {
    $sourceBefore[$short] = hash('sha256', serialize($db->query('SELECT * FROM '
        . $t($short) . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC)));
}
$saveJournal(['source_before' => $sourceBefore, 'phase' => 'baseline_saved']);
$restaurant = $db->query('SELECT LEFT_RESTAURANT_ID FROM '
    . $t('electronic_menu')
    . ' WHERE STORE_ID=10001 AND STATUS=1 AND IS_DELETE=0 ORDER BY ID')
    ->fetch(PDO::FETCH_ASSOC);
$restaurantId = (int)($restaurant['left_restaurant_id'] ?? 0);
if ($restaurantId <= 0) throw new RuntimeException('No safe restaurant relationship');
$deviceIds = $journal['device_ids'];
$q = $db->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu_device')
    . ' WHERE DEVICE_ID IN (?,?)');
$q->execute([$deviceIds[1], $deviceIds[2]]);
if ((int)$q->fetchColumn() !== 0) throw new RuntimeException('Virtual device marker collision');
$code = '';
$codeHash = '';
for ($attempt = 0; $attempt < 20; $attempt++) {
    $candidate = (string)random_int(100000, 999999);
    $candidateHash = hash('sha256', $candidate);
    $q = $db->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu_bind_code')
        . ' WHERE CODE_HASH=?');
    $q->execute([$candidateHash]);
    if ((int)$q->fetchColumn() === 0) {
        $code = $candidate;
        $codeHash = $candidateHash;
        break;
    }
}
if ($code === '') throw new RuntimeException('No collision-free synthetic bind code');
$menuUuid = strtoupper(bin2hex(random_bytes(16)));
$publicToken = bin2hex(random_bytes(32));
$now = date('Y-m-d H:i:s');
$db->prepare('INSERT INTO ' . $t('electronic_menu')
    . ' (UUID,PUBLIC_TOKEN,STORE_ID,STATUS,IS_DELETE,DISPLAY_MODE,'
    . ' LEFT_RESTAURANT_ID,RIGHT_RESTAURANT_ID,CAROUSEL_INTERVAL,'
    . ' CREATE_BY,CREATE_TIME,UPDATE_TIME)'
    . ' VALUES (?,?,10001,1,0,1,?,0,8,?,?,?)')
    ->execute([$menuUuid, $publicToken, $restaurantId, $marker, $now, $now]);
$q = $connect()->prepare('SELECT ID FROM ' . $t('electronic_menu')
    . ' WHERE UUID=? AND PUBLIC_TOKEN=? AND CREATE_BY=?');
$q->execute([$menuUuid, $publicToken, $marker]);
$menuIds = $q->fetchAll(PDO::FETCH_COLUMN);
if (count($menuIds) !== 1 || (int)$menuIds[0] <= 0) {
    throw new RuntimeException('Owned menu insert ambiguous');
}
$menuId = (int)$menuIds[0];
$saveJournal(['menu_id' => $menuId, 'menu_uuid' => $menuUuid,
    'public_token' => $publicToken, 'phase' => 'menu_inserted']);
$expiresAt = date('Y-m-d H:i:s', time() + 600);
$db->prepare('INSERT INTO ' . $t('electronic_menu_bind_code')
    . ' (MENU_ID,CODE_HASH,EXPIRES_AT,USED_AT,STATUS,STORE_ID,'
    . ' CREATE_BY,CREATE_TIME) VALUES (?,?,?,NULL,1,10001,?,?)')
    ->execute([$menuId, $codeHash, $expiresAt, $marker, $now]);
$q = $connect()->prepare('SELECT ID FROM ' . $t('electronic_menu_bind_code')
    . ' WHERE MENU_ID=? AND CODE_HASH=? AND CREATE_BY=?');
$q->execute([$menuId, $codeHash, $marker]);
$codeIds = $q->fetchAll(PDO::FETCH_COLUMN);
if (count($codeIds) !== 1 || (int)$codeIds[0] <= 0) {
    throw new RuntimeException('Owned bind-code insert ambiguous');
}
$codeId = (int)$codeIds[0];
$saveJournal(['code_id' => $codeId, 'code_hash' => $codeHash,
    'phase' => 'bind_code_inserted']);
$stage = 'two_concurrent_http_activate';
$saveJournal(['phase' => 'two_http_started']);
if (!extension_loaded('curl')) throw new RuntimeException('cURL multi unavailable');
$multi = curl_multi_init();
$handles = [];
$bodies = [1 => '', 2 => ''];
foreach ([1, 2] as $side) {
    $handle = curl_init('http://127.0.0.1:' . $ports[$side]
        . '/api/electronicMenu/device/activate');
    $form = http_build_query(['bind_code' => $code,
        'device_id' => $deviceIds[$side],
        'device_name' => 'Synthetic TV'], '', '&', PHP_QUERY_RFC3986);
    curl_setopt_array($handle, [CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $form,
        CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 15,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_WRITEFUNCTION => static function ($ch, string $chunk) use (&$bodies, $side): int {
            if (strlen($bodies[$side]) + strlen($chunk) > 1048576) return 0;
            $bodies[$side] .= $chunk;
            return strlen($chunk);
        }]);
    $handles[$side] = $handle;
    curl_multi_add_handle($multi, $handle);
}
$businessHttpSent = true;
$running = 0;
$startAt = microtime(true);
do {
    $multiCode = curl_multi_exec($multi, $running);
    if ($multiCode !== CURLM_OK || microtime(true) - $startAt > 20) break;
    if ($running > 0) curl_multi_select($multi, 0.1);
} while ($running > 0);
$http = [];
foreach ($handles as $side => $handle) {
    $http[$side] = ['status' => (int)curl_getinfo($handle, CURLINFO_HTTP_CODE),
        'curl_errno' => curl_errno($handle),
        'body' => json_decode($bodies[$side], true)];
    curl_multi_remove_handle($multi, $handle);
    curl_close($handle);
}
curl_multi_close($multi);
$failure = '';
try {
    if ($multiCode !== CURLM_OK || $running !== 0) {
        throw new RuntimeException('Two-worker HTTP completion unknown');
    }
    $successSide = 0;
    $rejectedSide = 0;
    foreach ($http as $side => $result) {
        if ($result['curl_errno'] !== 0 || $result['status'] !== 200
            || !is_array($result['body'])) {
            throw new RuntimeException('Two-worker HTTP transport/JSON invalid');
        }
        if (($result['body']['code'] ?? null) === 0) {
            if ($successSide !== 0) throw new RuntimeException('Two winners');
            $successSide = $side;
        } elseif (($result['body']['code'] ?? null) === 1
            && ($result['body']['data'] ?? null) === []
            && in_array((string)($result['body']['message'] ?? ''),
                ['绑定码无效或已过期', '绑定码已被使用'], true)) {
            if ($rejectedSide !== 0) throw new RuntimeException('Two expected losers');
            $rejectedSide = $side;
        } else {
            throw new RuntimeException('Unexpected activation business response');
        }
    }
    if ($successSide === 0 || $rejectedSide === 0
        || $successSide === $rejectedSide) {
        throw new RuntimeException('Exactly one winner and one loser not proven');
    }
    $winnerToken = (string)($http[$successSide]['body']['data']['device_token'] ?? '');
    if (!preg_match('/^[a-f0-9]{64}$/D', $winnerToken)) {
        throw new RuntimeException('Winning token contract invalid');
    }
    $state = json_decode((string)file_get_contents($barrierDir . '/state.json'), true);
    if (!is_array($state) || empty($state['arrivals'][1])
        || empty($state['arrivals'][2]) || ($state['released'] ?? null) !== true
        || ($state['aborted'] ?? null) !== false
        || empty($state['dispatch'][1]) || empty($state['dispatch'][2])) {
        throw new RuntimeException('Concurrent ingress not proven');
    }
    $arrivalDeltaMs = (int)round(abs($state['arrivals'][1]['time']
        - $state['arrivals'][2]['time']) * 1000);
    $dispatchDeltaMs = (int)round(abs($state['dispatch'][1]
        - $state['dispatch'][2]) * 1000);
    if ($dispatchDeltaMs > 500) {
        throw new RuntimeException('Private router dispatch not concurrently released');
    }
    $read = $connect();
    $q = $read->prepare('SELECT * FROM ' . $t('electronic_menu_bind_code')
        . ' WHERE ID=? AND CODE_HASH=? AND CREATE_BY=?');
    $q->execute([$codeId, $codeHash, $marker]);
    $claimed = $q->fetch(PDO::FETCH_ASSOC);
    if (!$claimed || (int)$claimed['status'] !== 2
        || $claimed['used_at'] === null
        || (int)$claimed['menu_id'] !== $menuId) {
        throw new RuntimeException('Bind code not claimed exactly once');
    }
    $q = $read->prepare('SELECT * FROM ' . $t('electronic_menu_device')
        . ' WHERE DEVICE_ID IN (?,?) ORDER BY ID');
    $q->execute([$deviceIds[1], $deviceIds[2]]);
    $deviceRows = $q->fetchAll(PDO::FETCH_ASSOC);
    if (count($deviceRows) !== 1
        || (string)$deviceRows[0]['device_id'] !== $deviceIds[$successSide]
        || (int)$deviceRows[0]['menu_id'] !== $menuId
        || (int)$deviceRows[0]['store_id'] !== 10001
        || (int)$deviceRows[0]['status'] !== 1
        || (string)$deviceRows[0]['device_token_hash']
            !== hash('sha256', $winnerToken)) {
        throw new RuntimeException('Winner/loser device original rows invalid');
    }
    $saveJournal(['phase' => 'one_winner_one_loser_observed']);
} catch (Throwable $error) {
    $failure = get_class($error) . ':' . hash('sha256', $error->getMessage());
}
$stage = 'two_worker_completion_barrier';
foreach ([1, 2] as $side) {
    $url = 'http://127.0.0.1:' . $ports[$side];
    $status = json_decode((string)@file_get_contents($url . '/__poc_race_status',
        false, stream_context_create(['http' => ['timeout' => 8]])), true);
    $boundary = json_decode((string)@file_get_contents($url . '/__poc_boundary',
        false, stream_context_create(['http' => ['timeout' => 8]])), true);
    if (!is_array($status) || !is_array($boundary)
        || (int)($status['pid'] ?? 0) !== (int)$journal['worker_pids'][$side]
        || (int)($status['side'] ?? 0) !== $side
        || !$ownsListener((int)$journal['worker_pids'][$side], $ports[$side])
        || ($boundary['external_stubs'] ?? null) !== true
        || ($boundary['redis_isolated'] ?? null) !== true
        || ($boundary['real_queue'] ?? true) !== false) {
        throw new RuntimeException('Late activation possible; retain all recovery assets');
    }
}
$saveJournal(['phase' => 'both_worker_http_barriers']);
$stage = 'precise_owned_cleanup';
$cleanup = $connect();
$q = $cleanup->prepare('SELECT ID,UUID,DEVICE_ID,DEVICE_TOKEN_HASH,MENU_ID,'
    . ' STORE_ID,CREATE_BY FROM ' . $t('electronic_menu_device')
    . ' WHERE DEVICE_ID IN (?,?) ORDER BY ID');
$q->execute([$deviceIds[1], $deviceIds[2]]);
$deviceRows = $q->fetchAll(PDO::FETCH_ASSOC);
if (count($deviceRows) > 1) throw new RuntimeException('Unexpected device cleanup scope');
foreach ($deviceRows as $row) {
    if (!in_array((string)$row['device_id'], $deviceIds, true)
        || (int)$row['menu_id'] !== $menuId
        || (int)$row['store_id'] !== 10001
        || (string)$row['create_by'] !== 'device-bind'
        || (string)$row['uuid'] === '') {
        throw new RuntimeException('Unrecognized device before cleanup');
    }
}
$q = $cleanup->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu_device_log')
    . ' WHERE MENU_ID=?');
$q->execute([$menuId]);
if ((int)$q->fetchColumn() !== 0) {
    throw new RuntimeException('Unexpected device log before cleanup');
}
$cleanup->beginTransaction();
foreach ($deviceRows as $row) {
    $q = $cleanup->prepare('DELETE FROM ' . $t('electronic_menu_device')
        . ' WHERE ID=? AND UUID=? AND DEVICE_ID=? AND DEVICE_TOKEN_HASH=?'
        . ' AND MENU_ID=? AND STORE_ID=10001 AND CREATE_BY=?');
    $q->execute([(int)$row['id'], (string)$row['uuid'],
        (string)$row['device_id'], (string)$row['device_token_hash'],
        $menuId, 'device-bind']);
    if ($q->rowCount() !== 1) throw new RuntimeException('Owned device delete not one');
}
$q = $cleanup->prepare('DELETE FROM ' . $t('electronic_menu_bind_code')
    . ' WHERE ID=? AND MENU_ID=? AND CODE_HASH=? AND CREATE_BY=?');
$q->execute([$codeId, $menuId, $codeHash, $marker]);
if ($q->rowCount() !== 1) throw new RuntimeException('Owned code delete not one');
$q = $cleanup->prepare('DELETE FROM ' . $t('electronic_menu')
    . ' WHERE ID=? AND UUID=? AND PUBLIC_TOKEN=? AND CREATE_BY=?');
$q->execute([$menuId, $menuUuid, $publicToken, $marker]);
if ($q->rowCount() !== 1) throw new RuntimeException('Owned menu delete not one');
if (!$cleanup->commit()) throw new RuntimeException('Owned cleanup commit uncertain');
$saveJournal(['phase' => 'cleanup_committed']);
$stage = 'independent_new_process_audit';
$auditEnv = $workerEnv;
$auditEnv['CDX_EM_RACE_LANE'] = $lane;
$auditEnv['CDX_EM_RACE_AUDIT'] = 'ROOT_APPROVED_RACE_INDEPENDENT_ZERO_V1';
$auditEnv['CDX_EM_RACE_AUDIT_SHA'] = (string)getenv('CDX_EM_RACE_AUDIT_SHA');
$auditEnv['CDX_EM_RACE_JOURNAL'] = $journalPath;
$auditArgs = [escapeshellarg($php)];
if ($lane === 'C') {
    foreach (['POC_DM_PHP_LIB', 'POC_DM_PHP_PDO'] as $key) {
        $auditArgs[] = '-d';
        $auditArgs[] = escapeshellarg('extension=' . $workerEnv[$key]);
    }
}
array_push($auditArgs, escapeshellarg($auditor), '--audit-zero');
$auditProcess = proc_open('exec ' . implode(' ', $auditArgs),
    [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
    $auditPipes, $barrierDir, $auditEnv);
if (!is_resource($auditProcess)) throw new RuntimeException('Independent audit unavailable');
fclose($auditPipes[0]);
$auditOut = stream_get_contents($auditPipes[1], 4097);
$auditErr = stream_get_contents($auditPipes[2], 1025);
fclose($auditPipes[1]);
fclose($auditPipes[2]);
$auditExit = proc_close($auditProcess);
$auditJson = is_string($auditOut) ? json_decode(trim($auditOut), true) : null;
if ($auditExit !== 0 || $auditErr !== '' || !is_array($auditJson)
    || ($auditJson['status'] ?? null) !== 'independent_zero_pass'
    || ($auditJson['lane'] ?? null) !== $lane) {
    throw new RuntimeException('Independent zero/fingerprint audit failed');
}
$saveJournal(['phase' => 'independent_zero_checked']);
$stage = 'stop_only_two_private_workers';
foreach ([1, 2] as $side) {
    if (!is_resource($processes[$side]) || !proc_terminate($processes[$side])) {
        throw new RuntimeException('Private worker termination uncertain');
    }
    proc_close($processes[$side]);
    if (is_dir('/proc/' . $journal['worker_pids'][$side])) {
        throw new RuntimeException('Private worker still present');
    }
}
$saveJournal(['phase' => 'workers_stopped']);
$stage = 'remove_only_private_roots_and_journal';
foreach ($workerRoots as $side => $path) {
    if ($path !== '/tmp/cdx-em-race-' . strtolower($lane)
            . '-' . $nonce . '-' . $side || realpath($path) !== $path) {
        throw new RuntimeException('Private root deletion target changed');
    }
    $removePrivateTree($path);
}
if ($barrierDir !== '/tmp/cdx-em-race-barrier-' . $nonce
    || realpath($barrierDir) !== $barrierDir) {
    throw new RuntimeException('Private barrier deletion target changed');
}
$removePrivateTree($barrierDir);
echo json_encode(['status' => $failure === ''
        ? 'scoped_race_pass' : 'scoped_race_fail',
    'lane' => $lane, 'concurrent_ingress' => $failure === '',
    'arrival_delta_ms' => $arrivalDeltaMs ?? null,
    'dispatch_delta_ms' => $dispatchDeltaMs ?? null,
    'one_winner_one_expected_loser' => $failure === '',
    'failure' => $failure, 'independent_zero' => true,
    'two_private_workers_stopped' => true,
    'private_roots_removed' => true], JSON_UNESCAPED_SLASHES), PHP_EOL;
if ($failure !== '') exit(1);
