make(Kernel::class)->bootstrap(); $database = $argv[1] ?? ''; $mode = $argv[2] ?? ''; $db = DB::connection(); if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database || $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) { throw new LogicException('Cycle contention requires disposable local PostgreSQL QA.'); } config(['requisition-expiry.qa_enabled' => true]); require_once __DIR__.'/../Support/ReceiptFixture.php'; if ($mode === 'scheduled-cycle') { $input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR); Carbon::setTestNow($input['clock']); if (auth()->check() || request()->hasSession()) { throw new RuntimeException('Scheduled proof must run without an authenticated session.'); } $scope = app(RequisitionExpiryRun::class); $denied = 0; foreach (['foreign_origin', 'budget_create', 'submit'] as $action) { try { $scope->execute($input['request'], function () use ($input, $action) { $actor = User::query()->findOrFail($input['owner']); if ($action === 'foreign_origin') { app(CommonBudget::class)->for($actor, [$input['request'] + 999999 => 1]); } elseif ($action === 'budget_create') { app(CommonBudget::class)->for($actor, [$input['request'] => 1])->create([]); } else { $request = Requisition::query()->findOrFail($input['request']); app(RequisitionWorkflow::class)->submit($actor, $request, (string) Str::uuid(), $request->process_version); } }); throw new RuntimeException('Scheduled scope unexpectedly allowed '.$action); } catch (HttpExceptionInterface $error) { if ($error->getStatusCode() !== 403 || $scope->tenantId() !== null) { throw $error; } $denied++; } } if (Artisan::call('sgc:approval-deadlines-tick') !== 0) { throw new RuntimeException('Scheduled deadline tick failed: '.Artisan::output()); } $request = $db->table('requisitions')->where('id', $input['request'])->sole(); $count = $db->table('supply_records')->count(); $audits = $db->table('audit_logs')->count(); if (Artisan::call('sgc:approval-deadlines-tick') !== 0 || $db->table('supply_records')->count() !== $count || $db->table('audit_logs')->count() !== $audits || $request->status !== 'draft' || $request->approval_cycle !== 2 || auth()->check() || app(RequisitionExpiryRun::class)->tenantId() !== null || (int) $db->table('budget_entries')->where('requisition_id', $input['request'])->sum('reserved_minor') !== 0) { throw new RuntimeException('Scheduled expiry must close the scope and replay without effects.'); } $audit = $db->table('audit_logs')->where('requisition_id', $input['request'])->where('action', 'requisition.expired_returned')->sole(); $data = json_decode($audit->after, true, 32, JSON_THROW_ON_ERROR); if (($data['execution']['mode'] ?? null) !== 'scheduled_approval_deadline' || $audit->ip_address !== null) { throw new RuntimeException('Scheduled audit must distinguish automatic execution from an interactive act.'); } echo json_encode(['scheduled_expiry_without_session' => true, 'scheduled_scope_closed' => true, 'scheduled_repeat_without_effects' => true, 'scheduled_audit_explicit' => true, 'scheduled_unrelated_operations_denied' => $denied], JSON_THROW_ON_ERROR); exit; } if ($mode === 'legacy-cycles') { $actor = User::query()->findOrFail((int) $argv[3]); auth()->guard()->setUser($actor); try { app(CommonBudget::class)->for($actor)->balance((int) $argv[4]); throw new RuntimeException('Old runtime unexpectedly exposed a balance after a new cycle.'); } catch (HttpExceptionInterface $error) { if ($error->getStatusCode() !== 503) { throw $error; } echo json_encode(['old_cycle_runtime_rejected_before_balance' => true, 'status' => 503]); } exit; } if ($mode === 'prepare') { if (! $db->getSchemaBuilder()->hasTable('budget_requisition_cycles')) { (require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up(); } $f = receiptFixture(); $owner = $f['issuer']; $admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]); $head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]); $finance = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Finance]); auth()->guard()->setUser($admin); Budget::query()->create(['tenant_id' => $owner->tenant_id, 'cost_center_id' => $f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Synthetic concurrent cycle budget', 'created_by' => $admin->id, 'approved_by' => $finance->id]); app(RequisitionExpiry::class)->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []]], 'reason' => 'Explicit synthetic concurrent expiry policy']); auth()->guard()->setUser($owner); $workflow = app(RequisitionWorkflow::class); $request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic simultaneous expiry and decision', 'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]); $workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version); $request->refresh(); Carbon::setTestNow(now()->addMinutes(31)); echo json_encode(['tenant' => $owner->tenant_id, 'owner' => $owner->id, 'head' => $head->id, 'request' => $request->id, 'version' => $request->process_version, 'clock' => now()->toIso8601String(), 'basis' => app(RequisitionExpiry::class)->deadline($request)['basis_hash'], 'operation' => (string) Str::uuid()], JSON_THROW_ON_ERROR); exit; } // Re-enter the native submission route before checking an older installed composition. $verifyLegacy = function (array $input) use ($db, $database): void { $owner = User::query()->findOrFail($input['owner']); auth()->guard()->setUser($owner); $request = Requisition::query()->findOrFail($input['request']); app(RequisitionWorkflow::class)->submit($owner, $request, (string) Str::uuid(), $request->process_version); $before = $db->table('budget_entries')->where('requisition_id', $request->id)->orderBy('id')->get()->toJson(); $budget = $db->table('budgets')->where('tenant_id', $owner->tenant_id)->where('cost_center_id', $request->cost_center_id)->sole(); $legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy-cycles', (string) $owner->id, (string) $budget->id], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => base_path('packages/budget-control')], timeout: 30); $legacy->mustRun(); $receipt = json_decode($legacy->getOutput(), true, 32, JSON_THROW_ON_ERROR); if (($receipt['old_cycle_runtime_rejected_before_balance'] ?? false) !== true || $before !== $db->table('budget_entries')->where('requisition_id', $request->id)->orderBy('id')->get()->toJson()) { throw new RuntimeException('Legacy cycle refusal must precede all balance exposure and financial writes.'); } echo $legacy->getOutput().PHP_EOL; }; if ($mode === 'write') { $input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR); Carbon::setTestNow($input['clock']); $db->select('select set_config(?, ?, false)', ['application_name', 'sgc_cycle_write_'.getmypid()]); $actor = User::query()->findOrFail($input['decision'] ? $input['head'] : $input['owner']); auth()->guard()->setUser($actor); try { $request = Requisition::query()->findOrFail($input['request']); $workflow = app(RequisitionWorkflow::class); if ($input['decision']) { $workflow->decide($actor, $request, 'approved', 'Synthetic decision after configured deadline', $input['operation'], $input['version']); } else { $workflow->expire($actor, $request, $input['basis'], $input['operation'], $input['version']); } echo json_encode(['status' => 200]); } catch (HttpExceptionInterface $error) { echo json_encode(['status' => $error->getStatusCode()]); } exit; } if ($mode !== 'race-cycles') { throw new InvalidArgumentException('Unknown cycle worker mode.'); } foreach (['same_operation', 'different_operations', 'late_decision'] 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->beginTransaction(); try { $db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail(); for ($index = 0; $index < 2; $index++) { $payload = $input + ['decision' => $scenario === 'late_decision' && $index === 1]; if ($scenario !== 'same_operation' && $index === 1) { $payload['operation'] = (string) Str::uuid(); } $worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($payload, 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_cycle_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 cycle writers must demonstrably wait on the company lock.'); } $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); $request = $db->table('requisitions')->where('id', $input['request'])->sole(); $returns = $db->table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', 'req_expiration')->count(); $reserve = (int) $db->table('budget_entries')->where('requisition_id', $input['request'])->sum('reserved_minor'); $approved = $db->table('approval_steps')->where('requisition_id', $input['request'])->where('decision', 'approved')->count(); if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $returns !== 1 || $reserve !== 0 || $request->status !== 'draft' || $request->approval_cycle !== 2 || $approved !== 0) { throw new RuntimeException('Concurrent expiry must preserve one return, zero reserve and no late approval: '.json_encode($statuses)); } echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked, 'returns' => $returns, 'reserve_minor' => $reserve, 'late_approvals' => $approved], JSON_THROW_ON_ERROR).PHP_EOL; } finally { if ($db->transactionLevel() > 0) { $db->rollBack(); } foreach ($workers as $worker) { if ($worker->isRunning()) { $worker->stop(); } } } } $verifyLegacy($input); $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30); $prepare->mustRun(); $scheduled = new Process([PHP_BINARY, __FILE__, $database, 'scheduled-cycle', $prepare->getOutput()], dirname(__DIR__, 2), timeout: 30); $scheduled->mustRun(); echo $scheduled->getOutput().PHP_EOL;