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

This commit is contained in:
2026-11-22 19:39:09 +02:00
parent 36dcfdf00c
commit db1615fac1
79 changed files with 4082 additions and 120 deletions
@@ -0,0 +1,15 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Tempo\Finance\Budget\BudgetControl;
// No database access or business commands: exercise the host's actual pre-load verification.
require dirname(__DIR__, 2).'/vendor/autoload.php';
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
try {
$app->make(Kernel::class)->bootstrap();
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage().PHP_EOL);
exit(1);
}
echo json_encode(['runtime' => realpath((new ReflectionClass(BudgetControl::class))->getFileName())], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -19,6 +19,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderParts = ($argv[2] ?? '') === 'order-parts';
$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,17 +64,23 @@ $preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
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()) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
}
$prepare = new Process([PHP_BINARY, __DIR__.'/budget-distribution-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __DIR__.($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);
$engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
$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);
$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);
@@ -100,8 +107,7 @@ try {
DB::setDefaultConnection('distribution_restore');
$restoredActor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($restoredActor);
$again = app(CommonBudget::class)->for($restoredActor)->amendDistribution($input['origin'], $input['plan'], $input['hash'],
'Explicit synthetic amendment preserved in backup.', $input['operation']);
$again = $apply(app(CommonBudget::class)->for($restoredActor));
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Recovered command was not replayed without new effects.');
}
@@ -122,7 +128,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' => 4, 'existing_balances_preserved' => true,
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $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 {
@@ -0,0 +1,154 @@
<?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, '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();
}
}
}
}