@@ -7,10 +7,15 @@ import { generateId } from '@sim/utils/id'
77import { sql } from 'drizzle-orm'
88import { drizzle } from 'drizzle-orm/postgres-js'
99import postgres from 'postgres'
10- import { afterAll , beforeAll , beforeEach , describe , expect , it } from 'vitest'
10+ import { afterAll , beforeAll , beforeEach , describe , expect , it , vi } from 'vitest'
1111import { USAGE_LEDGER_STATEMENT_TIMEOUT_MS } from '@/lib/billing/constants'
1212import { readLedgerBounded } from '@/lib/billing/core/ledger-read'
1313
14+ vi . mock ( '@/lib/billing/constants' , async ( importOriginal ) => ( {
15+ ...( await importOriginal < typeof import ( '@/lib/billing/constants' ) > ( ) ) ,
16+ USAGE_LEDGER_STATEMENT_TIMEOUT_MS : 1000 ,
17+ } ) )
18+
1419const schemaName = `ledger_read_${ generateId ( ) . replaceAll ( '-' , '' ) } `
1520const connection = postgres ( readTestDatabaseUrl ( ) , {
1621 max : 1 ,
@@ -79,6 +84,25 @@ describe('bounded ledger reads with PostgreSQL', () => {
7984 expect ( await observeRead ) . toBeLessThanOrEqual ( USAGE_LEDGER_STATEMENT_TIMEOUT_MS - 80 )
8085 } )
8186
87+ it ( 'rejects a ledger read whose connection wait exhausted the budget' , async ( ) => {
88+ let outcome : Promise < number > | undefined
89+ await connection . begin ( async ( ) => {
90+ outcome = readLedgerBounded ( database , async ( tx ) => {
91+ const rows = await tx . execute < { total : string } > (
92+ sql `select sum(cost) as total from ledger_probe`
93+ )
94+ return Number ( rows [ 0 ] . total )
95+ } )
96+ void outcome . catch ( ( ) => undefined )
97+ await sleep ( USAGE_LEDGER_STATEMENT_TIMEOUT_MS + 100 )
98+ } )
99+ if ( ! outcome ) throw new Error ( 'Ledger read was not started' )
100+ await expect ( outcome ) . rejects . toThrow ( 'Database read deadline exceeded' )
101+ expect ( await connection `select sum(cost)::text as total from ledger_probe` ) . toEqual ( [
102+ { total : '1.00' } ,
103+ ] )
104+ } )
105+
82106 it ( 'cannot replay a write under the read-retry policy' , async ( ) => {
83107 const error = await readLedgerBounded ( database , async ( tx ) => {
84108 await tx . execute ( sql `insert into ledger_probe values (999)` )
0 commit comments