"""Provider-free regression for browser budget reconciliation and request caps.""" import asyncio from decimal import Decimal import importlib.util import json from pathlib import Path import shutil from tempfile import TemporaryDirectory import httpx spec=importlib.util.spec_from_file_location('browser_budget',Path(__file__).with_name('browser-budget.py')) module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) async def main(): with TemporaryDirectory() as directory: root=Path(directory) for p in Path('.local-s2s-build/browser-paid').glob('*.json'): if p.name!='browser-paid-ledger.json':shutil.copyfile(p,root/p.name) calls=[] def upstream(request): calls.append(request) return httpx.Response(503) guard=module.BrowserBudget(root,upstream=httpx.MockTransport(upstream)) assert Decimal(guard.state['reserved_usd'])==Decimal('.689118333') assert Decimal(guard.state['maximum_cumulative_usd'])==Decimal('.901118333') def speech():return httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',json={'model':'google/gemini-3.8-flash-lite-tts','voice':'Kore','input':'سلام','response_format':'pcm'}) for _ in range(4):await guard.handle_async_request(speech()) try:await guard.handle_async_request(speech()) except ValueError:pass else:raise AssertionError('fifth TTS admitted') data=json.loads(calls[0].content) assert data['provider']['options']=={tag:{'maxOutputTokens':2048} for tag in ('google-ai-studio','google-vertex/global')} text='x'*9000 r=httpx.Request('POST','https://openrouter.ai/api/v1/chat/completions',json={'model':'openai/gpt-4.1-mini','messages':[{'role':'user','content':text}],'max_tokens':128}) await guard.handle_async_request(r) assert json.loads(calls[-1].content)['provider']['allow_fallbacks'] is False assert Decimal(json.loads(guard.path.read_text())['reserved_usd'])==Decimal('.849118333') try:module.BrowserBudget(root) except FileExistsError:pass else:raise AssertionError('ledger overwritten') await guard.close_owned() with TemporaryDirectory() as directory: root=Path(directory) for p in Path('.local-s2s-build/browser-repair-paid').glob('*.json'): if p.name!='browser-paid-ledger.json':shutil.copyfile(p,root/p.name) guard=module.BrowserBudget(root,upstream=httpx.MockTransport(lambda request:httpx.Response(503))) assert Decimal(guard.state['reserved_usd'])==Decimal('.807118333') assert Decimal(guard.state['maximum_cumulative_usd'])==Decimal('.995118333') assert guard.maximum_attempts=={'speech':4,'transcriptions':2,'completions':2} await guard.close_owned() print('PASS: billed reservation release, unknown reservations retained, cumulative cap, failed-attempt retention, exact TTS endpoint options, LLM input/routing and exclusive ledger') asyncio.run(main())