commit melhorias compras6
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
@@ -3,9 +3,16 @@
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportLandedCosts;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
@@ -18,8 +25,10 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
throw new LogicException('Recovery is restricted to disposable local PostgreSQL QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderParts = ($argv[2] ?? '') === 'order-parts';
$landedCosts = ($argv[2] ?? '') === 'landed-costs';
$f = receiptFixture();
$author = 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]);
@@ -63,24 +72,96 @@ $pg = static function (string $binary, array $arguments) use ($config): void {
$preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
budgetDistributionFixtureSchema();
if ($landedCosts) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
} else {
budgetDistributionFixtureSchema();
}
if ($orderParts) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
}
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
$unexpectedEffects = $landedCosts
? ($db->table('budget_landed_commands')->exists() || $db->table('budget_landed_entries')->exists())
: ($db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists());
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore || $unexpectedEffects) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
}
$prepare = new Process([PHP_BINARY, __DIR__.($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php'), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php')), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
$engine = app(CommonBudget::class)->for($actor);
$apply = static fn ($engine) => $orderParts
? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
$apply($engine);
$apply = static fn ($engine) => $landedCosts
? $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation'])
: ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']));
$applied = $apply($engine);
if ($landedCosts) {
foreach (['commit', 'consume'] as $kind) {
$engine->transitionLandedCosts($input['plan'], $input['version'], $applied['plan_hash'], $kind, (string) Str::uuid());
}
$money = ['subtotal_minor' => 500, 'tax_minor' => 0, 'total_minor' => 500, 'reference_subtotal_minor' => 500, 'reference_tax_minor' => 0, 'reference_total_minor' => 500];
$input['documents']['late'] = ['kind' => 'other_charge', 'id' => 2, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
'creditor_key' => 'synthetic-late-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic late cost for recovery'), ...$money];
$input['components'][] = ['component_key' => 'late', 'kind' => 'other', 'origin' => 'late', ...$money];
$input['amend_operation'] = (string) Str::uuid();
$apply = static fn ($engine) => $engine->amendLandedCosts($input['plan'], $input['version'], $applied['plan_hash'], $input['version'] + 1,
$input['components'], $input['documents'], $input['amend_operation']);
$amended = $apply($engine);
if ($amended['consumed_minor'] !== 2000 || $amended['reserved_minor'] !== 500 || $amended['phase'] !== 'mixed') {
throw new RuntimeException('The recovery fixture must retain a consumption and a separate late reservation.');
}
// Separate native documentary fixture; the core-only source declarations above are not native invoices.
// All three file roots belong to this freshly generated disposable recovery directory.
$privateLive = $directory.'/private-live';
$privateBackup = $directory.'/private-backup';
$privateRestore = $directory.'/private-restored';
File::ensureDirectoryExists($privateLive);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateLive, 'throw' => true]));
config(['import-landed-costs.qa_enabled' => true]);
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
supplyGrant($author, ['finance']);
auth()->guard()->setUser($f['issuer']);
$nativeImport = app(SupplyPlanning::class)->save($f['issuer'], 'import', supplyInput([
'purchase_order_id' => $f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic recovery jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary recovery',
]));
auth()->guard()->setUser($author);
$costs = app(ImportLandedCosts::class);
$nativeData = ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment', 'reference' => 'RECOVERY-QA-ONLY',
'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic documentary authority', 'currency' => 'MZN',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null,
'reason' => 'Synthetic private evidence recovery; no legal rate or payment.'];
$nativeDoc = $costs->recordDocument($author, $nativeImport, $nativeData,
UploadedFile::fake()->createWithContent('recovery.pdf', "%PDF-1.4\nSynthetic original QA bytes\n%%EOF"));
$correction = $costs->recordDocument($author, $nativeImport, [...$nativeData, 'operation_key' => (string) Str::uuid(),
'record_key' => $nativeDoc->record_key, 'version' => 1, 'subtotal_minor' => 2100, 'total_minor' => 2100],
UploadedFile::fake()->createWithContent('recovery-correction.pdf', "%PDF-1.4\nSynthetic corrected QA bytes\n%%EOF"));
$evidenceManifest = [];
foreach ([$nativeDoc, $correction] as $record) {
$evidence = $record->snapshot['evidence'];
$evidenceManifest[$evidence['path']] = $evidence['sha256'];
}
if (! File::copyDirectory($privateLive, $privateBackup)) {
throw new RuntimeException('Unable to back up isolated native evidence.');
}
foreach ($evidenceManifest as $path => $checksum) {
if (hash_file('sha256', $privateBackup.'/'.$path) !== $checksum) {
throw new RuntimeException('Private evidence backup differs from the frozen documentary hash.');
}
Storage::disk('local')->delete($path);
}
auth()->guard()->logout();
if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== 2) {
throw new RuntimeException('The recovery test must demonstrate actual loss of its two synthetic original files.');
}
}
auth()->guard()->setUser($author);
if (app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore) {
throw new RuntimeException('The original company budget changed while preparing another synthetic source.');
}
auth()->guard()->setUser($actor);
$afterColumns = [];
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
$afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
@@ -111,6 +192,31 @@ try {
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Recovered command was not replayed without new effects.');
}
if ($landedCosts) {
$position = app(CommonBudget::class)->for($restoredActor)->landedCostState($input['plan']);
if ($position['result']['consumed_minor'] !== 2000 || $position['result']['reserved_minor'] !== 500 || $position['result']['phase'] !== 'mixed') {
throw new RuntimeException('Restored per-origin positions do not match the preserved journal.');
}
if (! File::copyDirectory($privateBackup, $privateRestore)) {
throw new RuntimeException('Unable to restore private evidence into the separate QA root.');
}
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateRestore, 'throw' => true]));
auth()->guard()->logout();
$health = app(ImportCostDocumentHealth::class)->inspect();
if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== 2 || $health['files_checked'] !== 2) {
throw new RuntimeException('Restored native evidence did not match the restored SQL metadata.');
}
auth()->guard()->setUser(User::query()->findOrFail($author->id));
foreach ([$nativeDoc, $correction] as $record) {
$recovered = $costs->evidence(auth()->user(), $nativeImport, $record->id);
if ($recovered->snapshot['evidence']['sha256'] !== $evidenceManifest[$recovered->snapshot['evidence']['path']]) {
throw new RuntimeException('Private native download no longer resolves the preserved original version.');
}
}
echo json_encode(['private_original_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL;
}
DB::setDefaultConnection($default);
DB::purge('distribution_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
@@ -119,8 +225,10 @@ try {
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $columns) !== $before || $restored->getSchemaBuilder()->hasTable('budget_distributions')
|| $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
$unexpectedSchema = $landedCosts
? ($restored->getSchemaBuilder()->hasTable('budget_landed_commands') || $restored->getSchemaBuilder()->hasTable('budget_landed_entries'))
: ($restored->getSchemaBuilder()->hasTable('budget_distributions') || $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation'));
if ($fingerprint($restored, $columns) !== $before || $unexpectedSchema) {
throw new RuntimeException('Pre-extension recovery did not restore the original schema/data.');
}
DB::setDefaultConnection('distribution_restore');
@@ -128,7 +236,7 @@ try {
if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) {
throw new RuntimeException('Pre-extension recovery changed the native balance.');
}
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $orderParts ? 8 : 4, 'existing_balances_preserved' => true,
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $landedCosts ? 2 : ($orderParts ? 8 : 4), 'existing_balances_preserved' => true,
'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true,
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
@@ -28,8 +28,18 @@ require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$f = receiptFixture();
budgetDistributionFixtureSchema();
config(['budget-distributions.qa_enabled' => true]);
$partsMode = getenv('SGC_ORDER_PARTS_QA_ENABLED') === 'true';
if ($partsMode) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true]);
}
$users = [];
foreach (['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin] as $name => $role) {
$roles = ['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin];
if ($partsMode) {
$roles += ['receiver' => PurchasingRole::Warehouse, 'finance-reviewer' => PurchasingRole::Finance];
}
foreach ($roles as $name => $role) {
$users[$name] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'name' => 'QA sintética · '.$role->label(), 'email' => 'qa-'.$name.'@sgc.example.invalid', 'purchasing_role' => $role]);
}
@@ -43,7 +53,8 @@ foreach ([$f['r']->cost_center_id, $centre->id] as $id) {
}
$workflow = app(RequisitionWorkflow::class);
$requests = [];
foreach (['draft', 'award', 'foreign'] as $purpose) {
$partSuppliers = $partAwards = [];
foreach ($partsMode ? ['draft', 'award', 'award2', 'foreign'] : ['draft', 'award', 'foreign'] as $purpose) {
auth()->guard()->setUser($users['owner']);
$r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id,
'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade exclusivamente sintética para revisão visual '.$purpose,
@@ -72,11 +83,18 @@ foreach (['draft', 'award', 'foreign'] as $purpose) {
}
$quotes = [];
for ($index = 0; $index < 3; $index++) {
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id)->replicate();
$supplier->name = 'Fornecedor sintético '.$purpose.' '.$index;
$supplier->nuit = (string) (200000000 + count($requests) * 100 + $index);
$supplier->created_by = $users['buyer']->id;
$supplier->save();
if ($partsMode && $purpose === 'award2') {
$supplier = Supplier::query()->findOrFail($partSuppliers[$index]);
} else {
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id)->replicate();
$supplier->name = 'Fornecedor sintético '.$purpose.' '.$index;
$supplier->nuit = (string) (200000000 + count($requests) * 100 + $index);
$supplier->created_by = $users['buyer']->id;
$supplier->save();
if ($partsMode && $purpose === 'award') {
$partSuppliers[$index] = $supplier->id;
}
}
$actor = $users['buyer'];
auth()->guard()->setUser($actor);
$input = Request::create('/', 'POST', ['supplier_id' => $supplier->id, 'currency' => $purpose === 'foreign' ? 'USD' : 'MZN',
@@ -93,7 +111,7 @@ foreach (['draft', 'award', 'foreign'] as $purpose) {
app(QuotationController::class)->evaluate($input, $quote, $workflow);
}
}
if ($purpose === 'foreign') {
if ($purpose === 'foreign' || ($partsMode && in_array($purpose, ['award', 'award2'], true))) {
auth()->guard()->setUser($users['buyer']);
$award = app(PurchaseWorkflow::class)->select($users['buyer'], $r, ['quotation_id' => $quotes[0]->id,
'justification' => 'Proposta exclusivamente sintética para revisão visual.', 'delivery_date' => today()->addWeek()->toDateString(),
@@ -106,8 +124,13 @@ foreach (['draft', 'award', 'foreign'] as $purpose) {
app(PurchaseWorkflow::class)->decide($actor, $award, 'approved', null);
}
auth()->guard()->setUser($users['buyer']);
$order = app(PurchaseWorkflow::class)->issue($users['buyer'], $award);
if ($purpose === 'foreign') {
$order = app(PurchaseWorkflow::class)->issue($users['buyer'], $award);
} else {
$partAwards[$purpose] = $award->id;
}
}
}
echo json_encode(['synthetic_only' => true, 'draft' => $requests['draft']->id, 'award' => $requests['award']->id,
'foreign_order' => $order->id, 'users' => array_map(fn ($user) => $user->email, $users)], JSON_THROW_ON_ERROR).PHP_EOL;
'foreign_order' => $order->id, 'users' => array_map(fn ($user) => $user->email, $users),
...($partsMode ? ['order_parts_awards' => $partAwards, 'receipt_stock' => $f['stock']->id, 'receipt_warehouse' => $f['warehouse']->id] : [])], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,163 @@
<?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;
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 (($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 landed-cost effects.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 503 || (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, 'status' => 503,
'runtime_landed_version' => defined(BudgetControl::class.'::LANDED_COSTS_VERSION') ? BudgetControl::LANDED_COSTS_VERSION : null], JSON_THROW_ON_ERROR).PHP_EOL;
}
exit;
}
if (($argv[2] ?? '') === 'prepare') {
$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.
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
'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]]], 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 {
$result = app(CommonBudget::class)->for($actor)->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 (($argv[2] ?? '') !== 'race') {
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) {
$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++) {
$contender = $input;
if ($index === 1 && $scenario !== 'same_operation') {
$contender['operation'] = (string) Str::uuid();
if ($scenario === 'same_source_different_plan') {
$contender['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', '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 !== 1 || $audits !== 1 || $reserved !== 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, '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();
}
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}