make(Kernel::class)->bootstrap(); if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database || DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || (($argv[2] ?? '') !== 'legacy' && ! method_exists(BudgetControl::class, 'commitOrderParts'))) { throw new LogicException('Order-part contention requires the explicit common source and disposable local QA.'); } require_once __DIR__.'/../Support/ReceiptFixture.php'; require_once __DIR__.'/../Support/BudgetDistributionSchema.php'; require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php'; if (($argv[2] ?? '') === 'legacy') { $actor = User::query()->findOrFail((int) ($argv[3] ?? 0)); auth()->guard()->setUser($actor); try { app(CommonBudget::class)->for($actor); throw new RuntimeException('The old runtime must refuse balances with partial-order effects.'); } catch (HttpExceptionInterface $error) { if ($error->getStatusCode() !== 503 || method_exists(BudgetControl::class, 'commitOrderParts')) { throw $error; } echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503], JSON_THROW_ON_ERROR).PHP_EOL; } exit; } if (($argv[2] ?? '') === 'prepare') { $f = receiptFixture(); $source = unissuedOrderPartsSource($f, 10000); $line = $source->items()->sole(); $finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]); $reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]); auth()->guard()->setUser($finance); $budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 10000, 'reason' => 'Synthetic partial-order contention only.']); auth()->guard()->setUser($reviewer); app(CommonBudget::class)->for($reviewer)->approve($budget); auth()->guard()->setUser($f['issuer']); $engine = app(CommonBudget::class)->for($f['issuer']); $lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $plan = [['allocation_key' => 'synthetic', 'line_id' => $line->id, 'centre_id' => $f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]]; $engine->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid()); $award = $engine->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid()); echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'], 'order' => (string) Str::uuid(), 'operation' => (string) Str::uuid(), 'sources' => [['origin' => $source->id, 'version' => 0, 'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]], JSON_THROW_ON_ERROR); exit; } if (($argv[2] ?? '') === 'write') { $input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR); DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_order_parts_write_'.getmypid()]); $actor = User::query()->findOrFail($input['actor']); auth()->guard()->setUser($actor); try { $result = app(CommonBudget::class)->for($actor)->commitOrderParts($input['order'], $input['sources'], $input['operation']); echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR); } catch (BudgetFailure $error) { echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR); } catch (HttpExceptionInterface $error) { echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR); } exit; } if (($argv[2] ?? '') !== 'race') { throw new InvalidArgumentException('Invalid order-part worker mode.'); } budgetDistributionFixtureSchema(); (require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up(); foreach (['same_operation', 'conflicting_version'] as $scenario) { $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30); $prepare->mustRun(); $input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR); $workers = []; $db = DB::connection(); $db->beginTransaction(); try { $db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail(); for ($index = 0; $index < 2; $index++) { if ($index === 1 && $scenario === 'conflicting_version') { $input['operation'] = (string) Str::uuid(); $input['order'] = (string) Str::uuid(); $input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000; $input['sources'][0]['allocations'][0]['total_minor'] = 6000; } $worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30); $workers[] = $worker; $worker->start(); } $deadline = microtime(true) + 10; do { $db->select('select pg_stat_clear_snapshot()'); $blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_order_parts_write_%' and wait_event_type='Lock'", [$database])->n; if ($blocked >= 2) { break; } usleep(50000); } while (microtime(true) < $deadline); if ($blocked < 2) { throw new RuntimeException('Both contenders must demonstrably wait on the company lock.'); } $db->commit(); $results = []; foreach ($workers as $worker) { $worker->wait(); if (! $worker->isSuccessful()) { throw new RuntimeException($worker->getErrorOutput()); } $results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR); } $statuses = array_column($results, 'status'); sort($statuses); $entries = $db->table('budget_distribution_entries')->where('distribution_id', $input['source']); $reserved = (int) (clone $entries)->sum('reserved_minor'); $committed = (int) (clone $entries)->sum('committed_minor'); $commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->count(); $audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.orders_committed')->count(); if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1 || $reserved + $committed !== 10000 || ! in_array($committed, [4000, 6000], true) || ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) { throw new RuntimeException('Contention did not preserve one command, one audit and the exact original budget.'); } echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked, 'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved, 'committed_minor' => $committed], JSON_THROW_ON_ERROR).PHP_EOL; if ($scenario === 'same_operation') { $proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR); $legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => base_path($proof['path'])], timeout: 30); $legacy->mustRun(); echo $legacy->getOutput(); } } finally { if ($db->transactionLevel() > 0) { $db->rollBack(); } foreach ($workers as $worker) { if ($worker->isRunning()) { $worker->stop(); } } } }