Two of my AI agents shared one budget file and a charge vanished. Here is the SQLite fix
A reader pointed out a bug in a budget guard I posted: two agents can read the same budget_state.json , both pass the check, both write back, and one charge disappears. They were right. Here is why it happens and a fix you can copy. The bug: load, check, save is not atomic import json def charge ( amount , cap , path = " budget_state.json " ): state = json . load ( open ( path )) # agent A and…
Two AI agents were using the same budget file simultaneously. Each agent successfully passed the check and wrote their own changes back, causing one charge to vanish. This occurred because the load, check, and save operations were not atomic. To fix this issue, the code demonstrated how to use SQLite's atomic updates to reserve funds first in one statement, then commit the change.
By doing this, two agents cannot both slip under the budget cap. The fix includes a reserve function that ensures the cap is not exceeded and a refund function that only refunds the amount if the reservation never took place. Additionally, the code includes a BudgetExceeded exception to catch over-budget errors and a guarded_call function that reserves funds before making a call and refunds them if the call fails.
To prevent runaway retries, a FailureBreaker class tracks consecutive failures and raises an exception after a set number of attempts. The setup uses dollars as the main stop condition, with consecutive failures as an additional safeguard.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.