make(Kernel::class)->bootstrap(); if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || ! method_exists(BudgetControl::class, 'amendDistribution')) { throw new LogicException('Distribution concurrency requires the authorised common source and disposable QA database.'); } require_once __DIR__.'/../Support/ReceiptFixture.php'; require_once __DIR__.'/../Support/BudgetDistributionSchema.php'; if (($argv[2] ?? '') === 'prepare') { $f = receiptFixture(); $actor = 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]); $centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'code' => 'QA-RACE', 'name' => 'Synthetic race centre']); foreach ([$f['r']->cost_center_id, $centre->id] as $id) { auth()->guard()->setUser($actor); $budget = app(CommonBudget::class)->for($actor)->create(['cost_center_id' => $id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Synthetic concurrency budget only.']); auth()->guard()->setUser($reviewer); app(CommonBudget::class)->for($reviewer)->approve($budget); } auth()->guard()->setUser($actor); $plan = array_map(fn ($id) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $f['line']->requisition_item_id, 'centre_id' => $id, 'subtotal_minor' => 5000, 'total_minor' => 5000], [$f['r']->cost_center_id, $centre->id]); $lines = [$f['line']->requisition_item_id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $engine = app(CommonBudget::class)->for($actor); $engine->recordDistribution($f['r']->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid()); $commit = $engine->recordDistribution($f['r']->id, 'commit', $plan, $lines, str_repeat('a', 64), (string) Str::uuid()); $plan[0]['subtotal_minor'] = $plan[0]['total_minor'] = 6000; $plan[1]['subtotal_minor'] = $plan[1]['total_minor'] = 4000; echo json_encode(['tenant' => $actor->tenant_id, 'actor' => $actor->id, 'origin' => $f['r']->id, 'source' => $commit['distribution_id'], 'hash' => $commit['plan_hash'], 'plan' => $plan, 'operation' => (string) Str::uuid()], 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_distribution_write_'.getmypid()]); $actor = User::query()->findOrFail($input['actor']); auth()->guard()->setUser($actor); try { $result = app(CommonBudget::class)->for($actor)->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic Finance amendment under real contention.', $input['operation']); echo json_encode(['status' => 200, 'version' => $result['amendment_version'], '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 distribution worker mode.'); } budgetDistributionFixtureSchema(); 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['plan'][0]['subtotal_minor'] = $input['plan'][0]['total_minor'] = 5999; $input['plan'][1]['subtotal_minor'] = $input['plan'][1]['total_minor'] = 4001; } $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_distribution_write_%' and wait_event_type='Lock'", [$database])->n; if ($blocked >= 2) { break; } usleep(50000); } while (microtime(true) < $deadline); if ($blocked < 2) { throw new RuntimeException('Real contention was not demonstrated.'); } $db->commit(); $statuses = []; foreach ($workers as $worker) { $worker->wait(); if (! $worker->isSuccessful()) { throw new RuntimeException($worker->getErrorOutput()); } $statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status']; } sort($statuses); $snapshot = json_decode($db->table('budget_distributions')->where('id', $input['source'])->value('snapshot'), true, 32, JSON_THROW_ON_ERROR); if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $snapshot['amendment_version'] !== 1 || $db->table('budget_distribution_events')->where('distribution_id', $input['source'])->count() !== 3 || $db->table('budget_distribution_entries')->where('distribution_id', $input['source'])->count() !== 6 || $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.distribution_amended')->count() !== 1) { throw new RuntimeException('Version, effects, replay and unique audit were not demonstrated.'); } echo json_encode(['distribution_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'one_amendment_version_and_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL; } finally { if ($db->transactionLevel() > 0) { $db->rollBack(); } foreach ($workers as $worker) { if ($worker->isRunning()) { $worker->stop(); } } } }