Skip to main content

Reserved units of one deliverable: LedgerEntries::SourceSummary and EntitlementLotAllocations::ReservedBalance

Words used in this page​

WordMeaning
DeliverableThe product record that one spend pays for, such as one Ads::CampaignPlacement, called the source in the code.
The table billing_ledger_entriesOne row per movement of credits, with the deliverable in source_type and source_id, with the model LedgerEntry.
The table billing_entitlement_lot_allocationsOne row per lot that one ledger entry took credits from or gave credits to, with the model EntitlementLotAllocation.
The model EntitlementLotOne purchase of credits, with its own expires_at.
ReservedTaken from an EntitlementLot for a deliverable, and not yet consumed or released.
Direct spendA spend paid at once with consume_now, with no reserve first.
The balance row locklock('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.

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.md in jodapp-api: # typed: true, a sig per reader, no query.
ClassFields or method
EntitlementLotAllocations::ReservedBalance
One line: the units one deliverable still has reserved in one EntitlementLot
source_type
source_id
billing_entitlement_lot_id
lot_expires_at
units_reserved
lot_expired?(as_of:)
EntitlementLotAllocationService
The service that builds the lines, called only by SourceSummaryService
reserved_balances(source_type:, source_ids:)
LedgerEntries::SourceSummary
One header: the totals of one deliverable, with its lines
source_type
source_id
units_reserved
units_consumed
expired_as_of
reserved_balances
units_reserved_in_expired_lots
LedgerEntries::SourceSummaryService
The 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_of is the moment the read tested every EntitlementLot against.
  • units_reserved_in_expired_lots is a sum over the lines whose lot has expired, not a query.
  • lot_expired?(as_of:) is true when lot_expires_at is present and at or earlier than as_of.
    • It is the same test that release uses, so a lot with no expires_at never expires.

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 read builds 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.

QueryTableGroups byGives
1. Sum of reserved_deltabilling_ledger_entriessource_idunits_reserved of each header
2. Minus the sum of available_delta and reserved_delta of the consume entriesbilling_ledger_entriessource_idunits_consumed of each header
3. Sum of units_allocated with a sign: plus for a reserve allocation, minus for a consume or release allocationbilling_entitlement_lot_allocations, joined to its ledger entry and to billing_entitlement_lotssource_id
billing_entitlement_lot_id
billing_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 its consume allocation 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.

RaiseWherecode:title:debug_values
A line nets below 0reserved_balancesbilling_reserved_balance_below_zeroA lot nets below zero for this sourcesource_type
source_id
billing_entitlement_lot_id
units_reserved
The lines do not add up to the headerSourceSummaryService.readbilling_reserved_balances_mismatchThe per-lot balances do not add up to the reserved unitssource_type
source_id
units_reserved
the sum of the lines

Actors​

ActorWhat they do hereWhere
MarketingReads the three numbers of each placement in the cancel or reject dialog, then confirmsTeam Portal, the Ads campaign page, through GET /team/billing/spends
The daily consume jobConsumes the units of the day for each running placementAds::CampaignPlacements::ConsumeReservedCreditsJob, through EntitlementLotService.consume
The systemGives back or expires the reserved units when Marketing confirmsEntitlementLotService.release

Rules​

RuleApplies toExample
The units a deliverable has in a lot are its reserve allocations minus its consume and release allocations of entries with reserved_delta < 0 therealways901 in lot 10 on 2 Dec: 20 − 13 = 7
A lot that nets to exactly 0 gets no linealwaysA 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 droppedalwaysLot 10 at −5 raises billing_reserved_balance_below_zero
The lines of a deliverable add up to its units_reserved, or the read raisesalways7 + 10 = 17 for 901 on 2 Dec
One read tests every lot against one moment, because expired_as_of: is a required argumentalwaysThe 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 lockalways[901] and 100 ids both run 3 queries
The read returns one header per id that has ledger entries, in the order the ids camealwayssource_ids: [999, 901] with no entries for 999 returns one header, for 901
A direct spend counts in units_consumed and never makes a linealwaysconsume_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 EntitlementLotalwaysThe 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 idalwaysLot 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 nothingThe daily consume jobThe header of 901 lists lot 10 before lot 11
The lines of one lot over all deliverables add up to billing_entitlement_lots.units_reservedalwaysLot 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_elapsed is the number of full days since start_time, plus 1.
    • So the target rises by 1 at the first run of each day, and the other 23 runs consume nothing.
  1. On 20 Nov the reserve takes 30 units, ledger entry 5001 with entry_type: :reserve and reserved_delta: 30.
    • EntitlementLot 10 expires on 30 Nov 2026 and had 20 units available.
    • The reserve takes all 20 from lot 10 first, because it expires first.
    • EntitlementLot 11 expires on 31 Dec 2026, and the reserve takes the other 10 from it.
  2. 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: :consume and reserved_delta: -1.
    • After the run of 29 Nov, 901 has units_consumed: 10 and 10 units left in lot 10.
  3. On 30 Nov at 00:15 lot 10 passes its expires_at, and Billing::ExpireEntitlementLotsJob finds 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.
  4. On 30 Nov, 1 Dec and 2 Dec the job keeps taking 1 unit a day from lot 10.
  5. 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.
  6. 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 with lot_expired?: true, and lot 11 → 10 with lot_expired?: false.
  7. units_reserved_in_expired_lots is 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.
  8. If a bad write had left lot 10 at −5, reserved_balances would raise, and the check would never run.

Where the code is​

WhatFile in jodapp-apiEntry point
The lineapp/domains/billing/entitlement_lot_allocations/reserved_balance.rblot_expired?
The builder of the linesapp/domains/billing/entitlement_lot_allocation_service.rbreserved_balances
The headerapp/domains/billing/ledger_entries/source_summary.rbunits_reserved_in_expired_lots
The one builderapp/domains/billing/ledger_entries/source_summary_service.rbread
The codes and titles of the two raisesapp/domains/billing/error.rbBilling::Error::DEFINITIONS
The spends endpointapp/domains/billing/spends/team_index_manager.rbexecute
The cancel and the daily consumeapp/domains/billing/entitlement_lot_service.rbrelease
consume