Reserved units of one deliverable: LedgerEntries::SourceSummary and EntitlementLotAllocations::ReservedBalance
Words used in this page
| Word | Meaning |
|---|---|
| Deliverable | The product record that one spend pays for, such as one Ads::CampaignPlacement, called the source in the code. |
The table billing_ledger_entries | One row per movement of credits, with the deliverable in source_type and source_id, with the model LedgerEntry. |
The table billing_entitlement_lot_allocations | One row per lot that one ledger entry took credits from or gave credits to, with the model EntitlementLotAllocation. |
The model EntitlementLot | One purchase of credits, with its own expires_at. |
| Reserved | Taken from an EntitlementLot for a deliverable, and not yet consumed or released. |
| Direct spend | A spend paid at once with consume_now, with no reserve first. |
| The balance row lock | lock('FOR UPDATE') on the billing_entitlement_balances row, which consume and release take while they write. |
What it does
Billing computes the reserved units of each deliverable from the ledger on every read, in total and per EntitlementLot.
- No column stores the units that one deliverable has reserved in one lot.
LedgerEntries::SourceSummaryService.readis the one builder, and every reader calls it.- It returns one header per deliverable, and each header carries one line per
EntitlementLot.
A SourceSummary holds the totals of one deliverable, and each ReservedBalance holds one lot's part
The read is two plain Ruby objects and the two services that build them.
- Both objects are Plain Data Objects, section 8 of
app/domains/AGENTS.mdin jodapp-api:# typed: true, asigper reader, no query.
| Class | Fields or method |
|---|---|
EntitlementLotAllocations::ReservedBalanceOne line: the units one deliverable still has reserved in one EntitlementLot | source_typesource_idbilling_entitlement_lot_idlot_expires_atunits_reservedlot_expired?(as_of:) |
EntitlementLotAllocationServiceThe service that builds the lines, called only by SourceSummaryService | reserved_balances(source_type:, source_ids:) |
LedgerEntries::SourceSummaryOne header: the totals of one deliverable, with its lines | source_typesource_idunits_reservedunits_consumedexpired_as_ofreserved_balancesunits_reserved_in_expired_lots |
LedgerEntries::SourceSummaryServiceThe one builder of the headers with their lines | read(source_type:, source_ids:, expired_as_of:) |
Three names need more than the table says.
expired_as_ofis the moment the read tested everyEntitlementLotagainst.units_reserved_in_expired_lotsis a sum over the lines whose lot has expired, not a query.lot_expired?(as_of:)is true whenlot_expires_atis present and at or earlier thanas_of.- It is the same test that
releaseuses, so a lot with noexpires_atnever expires.
- It is the same test that
One SourceSummary has many ReservedBalance lines, as one LedgerEntry has many EntitlementLotAllocation rows.
Legend: Lavender nodes are stored rows, and orange nodes are plain Ruby objects that
readbuilds from them.
SourceSummaryService.read runs three grouped queries, whatever the number of ids
Query 3 runs inside EntitlementLotAllocationService.reserved_balances, and its signed sum gives each line.
| Query | Table | Groups by | Gives |
|---|---|---|---|
1. Sum of reserved_delta | billing_ledger_entries | source_id | units_reserved of each header |
2. Minus the sum of available_delta and reserved_delta of the consume entries | billing_ledger_entries | source_id | units_consumed of each header |
3. Sum of units_allocated with a sign: plus for a reserve allocation, minus for a consume or release allocation | billing_entitlement_lot_allocations, joined to its ledger entry and to billing_entitlement_lots | source_idbilling_entitlement_lot_idbilling_entitlement_lots.expires_at | Each line, with its lot_expires_at |
Query 3 counts a consume or release allocation only when its ledger entry has reserved_delta < 0.
- A direct spend writes
reserved_delta: 0, so itsconsumeallocation never makes a line. - A lot that a deliverable used but never reserved from sums below 0, so the read raises.
The read raises when a line is below 0, or when the lines do not add up to the header
Both raises are Errors::InternalServerError, with code: and title: from Billing::Error::DEFINITIONS.
| Raise | Where | code: | title: | debug_values |
|---|---|---|---|---|
| A line nets below 0 | reserved_balances | billing_reserved_balance_below_zero | A lot nets below zero for this source | source_typesource_idbilling_entitlement_lot_idunits_reserved |
| The lines do not add up to the header | SourceSummaryService.read | billing_reserved_balances_mismatch | The per-lot balances do not add up to the reserved units | source_typesource_idunits_reservedthe sum of the lines |
Actors
| Actor | What they do here | Where |
|---|---|---|
| Marketing | Reads the three numbers of each placement in the cancel or reject dialog, then confirms | Team Portal, the Ads campaign page, through GET /team/billing/spends |
| The daily consume job | Consumes the units of the day for each running placement | Ads::CampaignPlacements::ConsumeReservedCreditsJob, through EntitlementLotService.consume |
| The system | Gives back or expires the reserved units when Marketing confirms | EntitlementLotService.release |
Rules
| Rule | Applies to | Example |
|---|---|---|
The units a deliverable has in a lot are its reserve allocations minus its consume and release allocations of entries with reserved_delta < 0 there | always | 901 in lot 10 on 2 Dec: 20 − 13 = 7 |
| A lot that nets to exactly 0 gets no line | always | A cancel writes a release allocation for every lot, so 901 has no line after it |
| A lot that nets below 0 raises, and no line is dropped | always | Lot 10 at −5 raises billing_reserved_balance_below_zero |
The lines of a deliverable add up to its units_reserved, or the read raises | always | 7 + 10 = 17 for 901 on 2 Dec |
One read tests every lot against one moment, because expired_as_of: is a required argument | always | The dialog on 2 Dec passes expired_as_of: Time.current |
| The read runs three grouped queries for 1 id or 100 ids, so it stays short under the balance row lock | always | [901] and 100 ids both run 3 queries |
| The read returns one header per id that has ledger entries, in the order the ids came | always | source_ids: [999, 901] with no entries for 999 returns one header, for 901 |
A direct spend counts in units_consumed and never makes a line | always | consume_now writes reserved_delta: 0 and a negative available_delta |
An expire allocation is never counted, because the source of its expire entry is the EntitlementLot | always | The expire entry of 7 units that the cancel of 901 writes has lot 10 as its source, so the read of 901 never counts it |
Every spend takes units in one order: the soonest expires_at of the lot, then the earliest purchased_at, then the lowest lot id | always | Lot 10 pays every day of 901, and still pays after it expires on 30 Nov, because its lot_expires_at is the soonest |
The read returns the lines of each header in that order, so consume sorts nothing | The daily consume job | The header of 901 lists lot 10 before lot 11 |
The lines of one lot over all deliverables add up to billing_entitlement_lots.units_reserved | always | Lot 11 holds 10 units for 901 and has units_reserved: 10 with no other placement |
Worked example: placement 901 on 2 December
Acme's placement 901 costs 30 units and runs 30 days from 20 Nov 2026.
- So the daily consume job takes 1 unit a day.
- Every number below comes from these inputs and the code, so a test can copy them.
credit_cost_snapshot: 30,duration_days: 30,start_time:20 Nov 2026 at 00:00 Singapore time.- The job runs every hour at minute 20, and its target is
round(credit_cost_snapshot × days_elapsed ÷ duration_days).days_elapsedis the number of full days sincestart_time, plus 1.- So the target rises by 1 at the first run of each day, and the other 23 runs consume nothing.
- On 20 Nov the reserve takes 30 units, ledger entry 5001 with
entry_type: :reserveandreserved_delta: 30.EntitlementLot10 expires on 30 Nov 2026 and had 20 units available.- The reserve takes all 20 from lot 10 first, because it expires first.
EntitlementLot11 expires on 31 Dec 2026, and the reserve takes the other 10 from it.
- From 20 Nov to 29 Nov the job consumes 1 unit a day, all from lot 10.
- Ledger entries 5002 to 5011, one per day, each with
entry_type: :consumeandreserved_delta: -1. - After the run of 29 Nov, 901 has
units_consumed: 10and 10 units left in lot 10.
- Ledger entries 5002 to 5011, one per day, each with
- On 30 Nov at 00:15 lot 10 passes its
expires_at, andBilling::ExpireEntitlementLotsJobfinds no unit to expire in it.- The job expires only
units_available, and lot 10 has 0, because 901 reserved all 20. - The 10 units 901 holds in lot 10 stay reserved.
- The job expires only
- On 30 Nov, 1 Dec and 2 Dec the job keeps taking 1 unit a day from lot 10.
- Lot 10 still has the soonest
lot_expires_at, so it still sorts first. - Ledger entries 5012 to 5014, each
reserved_delta: -1. - Billing D15 — An admin can cancel a running ad campaign lets a campaign keep running on an expired lot.
- Lot 10 still has the soonest
- On 2 Dec at 10:00, Marketing opens the cancel dialog, and
SourceSummaryService.read(source_type: 'Ads::CampaignPlacement', source_ids: [901], expired_as_of: Time.current)runs. - The read returns one header for 901.
units_reserved: 17, from +30 − 13 on the ledger entries.units_consumed: 13.reserved_balances: lot 10 → 7 withlot_expired?: true, and lot 11 → 10 withlot_expired?: false.
units_reserved_in_expired_lotsis 7, the line of lot 10, and the check passes because 7 + 10 = 17.- The dialog shows 10 units that go back, 7 that expire and 13 already used.
- If a bad write had left lot 10 at −5,
reserved_balanceswould raise, and the check would never run.
Where the code is
| What | File in jodapp-api | Entry point |
|---|---|---|
| The line | app/domains/billing/entitlement_lot_allocations/reserved_balance.rb | lot_expired? |
| The builder of the lines | app/domains/billing/entitlement_lot_allocation_service.rb | reserved_balances |
| The header | app/domains/billing/ledger_entries/source_summary.rb | units_reserved_in_expired_lots |
| The one builder | app/domains/billing/ledger_entries/source_summary_service.rb | read |
| The codes and titles of the two raises | app/domains/billing/error.rb | Billing::Error::DEFINITIONS |
| The spends endpoint | app/domains/billing/spends/team_index_manager.rb | execute |
| The cancel and the daily consume | app/domains/billing/entitlement_lot_service.rb | releaseconsume |
Related pages
- Billing D2 — All stored-value credits use entitlement lots; placement is not pooled: the spend order of the lots.
- The three readers of
SourceSummaryService.read: the dialog, the cancel and the daily consume - Billing D8 — No hold table: a deliverable's reserved credits are computed from the ledger
- Billing D12 — A running service cannot be cancelled, and released credits get no extra time
- Billing D15 — An admin can cancel a running ad campaign: the cancel in the worked example.
- Billing D18 — Product domains spend credits only through SpendService
- Billing interface for product domains — A product page reads Billing data from a Billing endpoint: the spends endpoint.