AI request cost: estimates, actual usage and the budget boundary
Separate estimates from received counters and reconciled cost, reserve budget in a MySQL/InnoDB transaction before dispatch, and preserve uncertainty after a timeout.
Two requests see a remaining budget of 100 at the same time. Each needs to reserve 60, and each looks admissible on its own. If checking and recording do not share an atomic boundary, both can start work. A later spending report cannot undo calls that have already happened. An AI task's budget therefore starts with a decision before dispatch and ends with reconciliation of the received data.
This analysis needs no paid request. The canonical Symfony SpendLab example uses the invented LAB currency, a synthetic price card, and a fake provider. The scenario uses MySQL 8.4/InnoDB through native PDO: it makes no real provider calls, and invoice cost is unknown. A MySQL connection is not an external AI service call. The numbers below do not describe model prices or a bill for real work.
Four records that answer different questions
An estimate answers how much a given plan may need. A reservation shows which part of the local budget has already been promised to this request. Received counters describe usage as reported by the provider. The reconciled cost is the result of our calculation using a specified price card. Even when two values coincide, their origins remain different.
It is especially important not to manufacture a provider-reported amount from our own calculation. If a response contains only token counts, reported_cost stays null. We can derive reconciled_cost separately. When another synthetic case reports 43 while the local calculation produces 40, the journal preserves both numbers. The difference needs an explanation; automatically relabelling one as the other would hide the question.
Such a journal does not confirm that an invoice has been paid either. It contains no taxes, discounts, or other categories outside the declared price card. A real integration first needs an exact mapping of a particular provider's fields, units, and accounting rules. A value from another model or route cannot be substituted merely because its name looks similar.
Pin the price card to the request
The teaching card, orchid-lab-v1, contains a route, effective date, currency, scale, and three rates. For every 1000 units, uncached input costs 10 LAB micro-units, cached input costs 5, and output costs 20. All rates are invented. The input categories here are mutually exclusive: cached tokens are not added to the total input a second time.
The estimate for 4000 units of uncached input and 1000 units of output is 60. A synthetic result with 2000 units of that input and 1000 units of output produces 40. The reduction comes from different counters, rather than a price change after execution. If a new card increases the output rate, the old request is still reconciled against its own saved version.
We must pin the card's actual significant data. A link to a “current price” record is insufficient if that record can be overwritten. In the example, the normalised card is stored in the request row. Its version is checked when reconciling the response. A mismatch does not trigger a silent recalculation: it stops acceptance of that result.
Integers need rules too
The example's money arithmetic uses no binary fractions. Each category is first multiplied by its rate, the result is divided by the scale, and any remainder is rounded up. The parts are then added. Rounding happens separately for each category. Three very small nonzero parts can therefore produce 3, even though rounding their combined fractional sum would produce a different number.
This is the chosen policy of the teaching price card, and it must be matched to the source of real prices. It should not emerge accidentally from a formatting function's behaviour. Boundary checks include one unit in each category, zero, and a value capable of overflowing multiplication. A negative number, boolean, fractional number, or numeric string is not accepted as a ready-to-use counter.
The PHP integer documentation explains the type's limits and conversion of an overflowing result to float. The permitted bound is therefore checked before multiplication, and addition checks for overflow too. declare(strict_types=1) alone does not make arithmetic safe. An invalid result is rejected before the budget changes, and the unresolved reservation remains visible.
A reservation must survive dispatch
The store has spent and reserved portions. The available amount is the budget minus both portions. Checking availability and creating a reservation happen in one InnoDB transaction with the budget row locked. Competing decisions for that budget are serialised: another worker must account for the reservation already committed. Reading the balance separately and then making an independent write cannot provide this.
The example uses native InnoDB transactions and locks. The MySQL documentation on InnoDB error handling covers lock wait timeouts and deadlocks, among other failures. Native errors 1205 and 1213 propagate to the caller; the code rolls back the transaction it owns. This is not a budget denial: a storage error means no decision was reached, whereas a budget denial means the available amount really was insufficient.
After the reservation commits, the start of dispatch is recorded separately. Only then is the fake handler called. This creates a clear boundary for a crash between steps. A reservation without dispatch can still be cancelled based on confirmed local state. A recorded dispatch start needs more careful investigation: an external effect may have happened even if the response was not saved.
Two processes instead of two sequential calls
The main scenario starts two independent PHP processes. Each opens its own native PDO connection to the same MySQL schema and announces readiness. Only after both are ready does the parent process let them proceed to reservation. The check therefore does not substitute two sequential calls on an object in memory for concurrency.
Run demo:spend-budget through the guarded bash fixtures/mysql_labs/run.sh wrapper, which supplies the MySQL lab environment. The scenario uses two distinct worker PIDs: one request is admitted and the other denied for budget. The fake handler is called once; a separate connection first checks the committed reservation of 60. The printed and saved results must match. A process startup error, nonzero exit, or violation of the readiness protocol stops the scenario and does not count as a budget denial.
| Scenario step | Spent | Reserved | Available |
|---|---|---|---|
| Initial state | 0 | 0 | 100 |
| One request admitted | 0 | 60 | 40 |
| Result for 40 accepted | 40 | 0 | 60 |
| Same response repeated | 40 | 0 | 60 |
This table defines the scenario's checked outcome: reconciliation for 40 leaves a budget of 100, spent 40, reserved 0, and available 60; an exact replay adds no evidence. The race between separate processes checks reservation in a shared MySQL/InnoDB schema, not a provider gateway or a distributed limit across multiple accounts.
The tests use the shared App\Infrastructure\MysqlLab helper in a guarded disposable MySQL 8.4 environment. A separate migrator explicitly prepares the InnoDB tables and constraints before business transactions begin; runtime code performs DML only and has no CREATE, ALTER, or DROP privileges. MySQL DDL can implicitly commit a transaction, so this is neither an atomic schema upgrade nor automatic data copying from the old SQLite store. Checks cover competing admissions, reservation persistence, and unchanged accounting on exact replay; application-wide test totals are not this article's test count.
A separate question is the boundary of the budget itself. In the example, an isolated lab schema represents one synthetic account and one accounting period. A product must explicitly decide whether a limit belongs to a customer, website, task, or a combination of them. Two different keys for a limit that is actually shared would again allow the same amount to be promised twice. Combining unrelated limits would instead create unjustified denials. A correct transaction within each individual key cannot fix that mistake.
The period boundary must not erase unresolved requests either. If dispatch starts before the month changes and usage data arrives afterwards, a rule must bind it to the original reservation. The teaching model deliberately does not advance the calendar or move debts between accounts. These decisions need to be added with corresponding scenarios before local arithmetic is used to account for a real product.
A repeat does not create another expense
A request's identity is bound to the reservation amount and price card. A repeat with the same data returns the existing record. Trying to use the same identifier for a different amount is a conflict. The transition to dispatch is controlled separately, so retrieving the record again does not itself authorise another handler call.
After reconciliation, a fingerprint of the normalised response is retained. An exact repeat changes neither the amount nor the journal. A repeat with different counters is rejected as a conflict. If a response belongs to another request, has the wrong currency, or contains an unknown billable category, the current accounting also remains unchanged. Continuing with an incomplete set of fields would silently reduce the cost.
A regression check rejects reuse of a receipt ID for another request without changing state; a valid second receipt reconciles total spent to 80, reserved to 0, and available to 20. Another check uses an optional Closure test seam, not the public command, to confirm result_receipt_write_failed for false or a short receipt write.
Unknown outcomes and overruns remain visible
A timeout does not automatically release the reservation. A missing response does not mean zero usage. The request enters an unknown state and awaits reconciliation. Restarting the state reader must not lose that reservation, and the expiry of a local timer does not prove that the provider did nothing. The model makes no automatic repeat calls.
Another control case produces a reconciled amount of 120 against a reservation of 60 and a budget of 100. The journal must record all 120, show an available balance of −20, and stop new admissions and dispatches. Clipping the amount to 60 would create a tidy table at the expense of the truth. A local reservation controls the start of work; it does not become a guarantee of the provider's final bill.
Moving to a real integration requires its own evidence that usage counters, prices, generation limits, and external reconciliation match. The prepared example helps check the foundation: when funds are promised, what is actually known about usage, and why repeats, uncertainty, and overruns must not disappear from the accounting.
The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.
Check the current example against an owned disposable MySQL schema:
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/SpendLab