Files
compras/tests/Concurrency/budget-landed-cost-worker.php
T
nala e709d900d1
tests / ci (push) Waiting to run
commit compras 2711
2026-11-27 13:49:31 +02:00

206 lines
14 KiB
PHP

<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->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, 'reserveLandedCosts'))) {
throw new LogicException('Landed-cost contention requires the approved common source and isolated local QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
if (in_array($argv[2] ?? '', ['legacy', 'legacy-estimate'], true)) {
$legacyEstimate = ($argv[2] ?? '') === 'legacy-estimate';
$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 landed-cost effects.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 503 || ($legacyEstimate ? defined(BudgetControl::class.'::IMPORT_ESTIMATE_VERSION')
: (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT))) {
throw $error;
}
echo json_encode(['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => $legacyEstimate, 'status' => 503,
'runtime_landed_version' => defined(BudgetControl::class.'::LANDED_COSTS_VERSION') ? BudgetControl::LANDED_COSTS_VERSION : null], JSON_THROW_ON_ERROR).PHP_EOL;
}
exit;
}
if (in_array($argv[2] ?? '', ['prepare', 'prepare-estimate', 'prepare-reconcile'], true)) {
$f = receiptFixture();
$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::Finance]);
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' => 20000, 'reason' => 'Explicit synthetic additional-origin contention.']);
auth()->guard()->setUser($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
$money = ['subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000];
// Contract fixture, not a native document upload or statutory customs action.
$prepared = ['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
'estimate' => in_array($argv[2] ?? '', ['prepare-estimate', 'prepare-reconcile'], true), 'reconciliation' => ($argv[2] ?? '') === 'prepare-reconcile', 'requisition' => $f['r']->id,
'version' => 1, 'operation' => (string) Str::uuid(),
'documents' => ['customs' => ['kind' => 'customs_assessment', 'id' => 1, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
'creditor_key' => 'synthetic-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic customs source'), ...$money]],
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]];
if ($prepared['reconciliation']) {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
auth()->guard()->setUser($finance);
$estimate = app(CommonBudget::class)->for($finance)->reserveImportEstimate($prepared['plan'], 1, $budget, $f['r']->id,
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, (string) Str::uuid());
$prepared += ['estimate_hash' => $estimate['plan_hash'], 'actual_plan' => (string) Str::uuid(), 'actual_operation' => (string) Str::uuid()];
}
echo json_encode($prepared, 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_landed_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$engine = app(CommonBudget::class)->for($actor);
if ($input['reconciliation'] ?? false) {
$result = $engine->reconcileImportEstimate($input['plan'], $input['version'], $input['estimate_hash'], 1, 1000,
$input['actual_plan'], 1, $input['budget'], $input['components'], $input['documents'], $input['operation'], $input['actual_operation']);
} elseif ($input['estimate'] ?? false) {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
$result = $engine->reserveImportEstimate($input['plan'], $input['version'], $input['budget'], $input['requisition'],
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, $input['operation']);
} else {
$result = $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $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 (! in_array($argv[2] ?? '', ['race', 'race-estimate', 'race-estimate-reconcile'], true)) {
throw new InvalidArgumentException('Invalid landed-cost worker mode.');
}
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
$prepareMode = match ($argv[2] ?? '') {
'race-estimate-reconcile' => 'prepare-reconcile', 'race-estimate' => 'prepare-estimate', default => 'prepare'
};
$prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode], 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++) {
$contender = $input;
if ($index === 1 && $scenario !== 'same_operation') {
$contender['operation'] = (string) Str::uuid();
if ($scenario === 'same_source_different_plan') {
$contender[($input['reconciliation'] ?? false) ? 'actual_plan' : 'plan'] = (string) Str::uuid();
} else {
$contender['version'] = 2;
}
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($contender, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$worker->start();
$workers[] = $worker;
}
$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_landed_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 writers must observably 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);
$commands = $db->table('budget_landed_commands')->where('tenant_id', $input['tenant'])->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', ($input['reconciliation'] ?? false) ? 'budget.landed_estimate_reconcile' : (($input['estimate'] ?? false) ? 'budget.landed_estimate_reserve' : 'budget.landed_reserve'))->count();
$reserved = (int) $db->table('budget_landed_entries')->where('tenant_id', $input['tenant'])->sum('reserved_minor');
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== (($input['reconciliation'] ?? false) ? 3 : 1) || $audits !== 1 || $reserved !== (($input['reconciliation'] ?? false) ? 3000 : 2000)
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention must retain exactly one source, budget effect and audit.');
}
echo json_encode(['scenario' => $scenario, 'estimate' => $input['estimate'] ?? false, 'reconciliation' => $input['reconciliation'] ?? false, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$artifact = 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($artifact['path'])], timeout: 30);
$legacy->mustRun();
$legacyResult = json_decode($legacy->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($legacyResult['old_runtime_rejected_before_balance'] ?? false) !== true) {
throw new RuntimeException('The installed V1 compatibility refusal was not demonstrated.');
}
echo $legacy->getOutput();
$wholeSource = base_path('storage/framework/testing/budget-landed-whole-source-qa-20261122');
if (hash_file('sha256', $wholeSource.'/src/BudgetLandedCosts.php') !== '583e8a01097398d3acd9985d7c5d6727f62e5877bb4a7cd6be82a86fd190ced8') {
throw new RuntimeException('Preserve the frozen whole-source QA runtime used for downgrade verification.');
}
$whole = new Process([PHP_BINARY, __FILE__, $database, 'legacy', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => $wholeSource], timeout: 30);
$whole->mustRun();
$wholeResult = json_decode($whole->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($wholeResult['old_runtime_rejected_before_balance'] ?? false) !== true || ($wholeResult['runtime_landed_version'] ?? null) !== 'COMMON-BUDGET-LANDED-COST-QA-v1') {
throw new RuntimeException('The earlier whole-command runtime must refuse the new per-origin data.');
}
echo $whole->getOutput();
if ($input['estimate'] ?? false) {
$prior = base_path('storage/framework/testing/budget-import-estimate-prior-qa-20261127');
if (hash_file('sha256', $prior.'/src/BudgetControl.php') !== 'd81f8fb172683727c221395224cecf9acb8285ab94e71e914141d41cf9e79efa') {
throw new RuntimeException('Preserve the private prior runtime used for estimate downgrade verification.');
}
$oldEstimate = new Process([PHP_BINARY, __FILE__, $database, 'legacy-estimate', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => $prior], timeout: 30);
$oldEstimate->mustRun();
$receipt = json_decode($oldEstimate->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($receipt['old_estimate_runtime_rejected'] ?? false) !== true || ($receipt['runtime_landed_version'] ?? null) !== CommonBudget::LANDED_COSTS_CONTRACT) {
throw new RuntimeException('The prior per-origin runtime must refuse estimate effects before balance access.');
}
echo $oldEstimate->getOutput();
}
}
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}