Every generator in Studio costs real money to run: model calls, image generation, rendering. A workspace pays in credits. The awkward property of generation is that the cost is incurred up front and the result arrives minutes later, or does not arrive. This page is about charging for something that might fail, and giving the money back exactly once when it does.

The flow

A row of four boxes: request, where a workspace asks for an article; deduct, under a reference made of the document id plus a per-attempt nonce; run, the pipeline in a background task; and kept, where the charge stands on success. From deduct a dashed arrow leads down to 402: not enough credits, and the new document is deleted. From run an arrow labelled failure leads down to refund, by the same reference and skipped if already refunded, which leads to a refund lot, a lot with no expiry. Two notes. Lots hold the balance: credits live in lots with a source and an expiry, a charge consumes the lots that expire soonest first, the ledger is a journal of what happened, and the workspace's balance field is a cache of the lots. Why a nonce: a retry of the same document is a new attempt, and with the document id alone as the reference the second attempt's refund would be taken for a repeat of the first.
Figure 1. A run from request to refund. Credits are deducted before the pipeline starts, under a reference unique to the attempt. A failure refunds by that reference, and a second refund for the same reference is skipped.
  1. The route creates the document for the thing being generated.
  2. It deducts the price. If the workspace cannot pay, the document is deleted again and the request is answered 402.
  3. It starts the pipeline as a background task, passing the reference it charged under.
  4. If the pipeline raises, its error path refunds by that reference. Two failures fall outside this: a second phase started by confirming an outline carries no reference, and a run that dies with the process is marked failed by the sweeper. Neither is refunded.

Charging first is deliberate. Charging on success would mean that a workspace with no credits could start any number of expensive runs and only be stopped when they finished.

Lots and a ledger

Two collections hold the money, and they have different jobs.

CollectionIsHolds
Credit lotsThe balanceOne row per grant of credits: its source, the amount, how much remains, when it was granted, when it expires
Credit ledgerThe journalOne row per event: workspace, signed amount, balance after, type, pipeline, reference, time

A comment at the top of the lot model states the division: the lot is the truth of the balance, and the ledger is the audit journal. The balance field on the workspace is a cache that is recomputed from the lots.

Why lots. Credits are not all alike. Credits from a subscription, credits bought as a top-up and credits returned as a refund have different lifetimes: purchased credits expire after 30 days, and a refund never expires. A single balance number cannot say which credits a charge should use. Lots can.

A deduction runs in this order.

  1. Backfill a lot for any balance that predates lots.
  2. Expire lots whose date has passed.
  3. Consume from the lots that expire soonest, first in first out.
  4. Recompute the cached balance.
  5. Write the ledger row.

Spending the soonest-to-expire credits first is the customer-friendly order. A customer with 100 credits expiring tomorrow and 100 expiring next month keeps the ones that last.

The reference

Every charge carries a reference, and the refund is found by it. What the reference is made of turned out to be the subtle part.

The obvious reference is the document id. One article, one charge, one possible refund. That breaks on retries.

Sequence with the document id as referenceResult
Attempt 1 is charged, fails, is refundedCorrect
The user retries. Attempt 2 is charged under the same reference, and failsThe refund finds an existing refund for that reference and skips. The user has paid for a failed run

So the reference is the document id plus a nonce generated for each paid attempt. Each attempt is its own charge with its own possible refund. A retry that the system offers for free passes no reference, and so can never trigger a refund of the original charge.

Two tests pin both sides: one shows that a shared document-id reference under-refunds the second attempt, and one shows that the per-request nonce does not.

A refund that happens once

The refund function is a sequence of guards, each returning early.

already_refunded = await CreditLedger.find_one(
    CreditLedger.workspace_id == workspace_id,
    CreditLedger.pipeline == pipeline,
    CreditLedger.reference_id == reference_id,
    CreditLedger.type == "refund",
)
if already_refunded:
    return True

matching_deduct = await CreditLedger.find_one(
    CreditLedger.workspace_id == workspace_id,
    CreditLedger.pipeline == pipeline,
    CreditLedger.reference_id == reference_id,
    CreditLedger.type == "deduct",
)

Logging between the two queries is removed here.

GuardWhy
No workspace, or a price of zeroNothing was charged
An empty referenceWithout a reference a refund cannot be matched, so none is made
A refund row already exists for this workspace, pipeline and referenceThe refund has been made. A pipeline’s error path can run twice
No deduct row exists for itNothing was charged for this attempt, for example a free retry

Only after all four does the function issue a lot. The refund lot has no expiry, because the customer should not lose refunded credits to a clock they did not start.

Workspaces

Credits belong to a workspace, not a user. A user can be a member of several workspaces with a role in each: owner, admin, member or viewer.

The workspace for a request is resolved by a dependency. The resolver used on ownership and write paths works as follows.

CaseResolved workspace
The request names a workspaceThat workspace, after a membership check
It names noneThe user’s oldest membership
A guestA synthetic id unique to that guest
A user with no workspaceA synthetic id unique to that user

Queries then filter by that id. Plans attach to the workspace and set its credit allowance, with one plan unmetered.

Tests

TestAsserts
test_refund_credits_idempotent_same_reference_idA second refund for one reference is skipped
test_refund_credits_different_reference_id_not_dedupedTwo attempts are refunded separately
test_refund_credits_empty_reference_id_is_noopNo reference, no refund
test_refund_credits_without_matching_deduct_is_noopNothing charged, nothing refunded
test_refund_credits_survives_balance_resyncA refund is still there after the cached balance is recomputed
test_shared_doc_id_reference_would_under_refund_second_attemptThe document id alone is the wrong reference
test_per_request_nonce_avoids_same_doc_under_refundThe nonce fixes it
test_article_free_retry_failure_does_not_refund_original_paid_createA free retry cannot refund the original charge
test_guest_resolves_to_isolated_synthetic_idThe strict resolver gives a guest its own synthetic id

Failure modes

What happensWhat the system does
The workspace cannot pay402, and the half-created document is removed
The pipeline raises in the run that was chargedRefunded by the attempt’s reference
The pipeline raises after the outline was confirmedNot refunded: the second phase carries no reference
The process dies mid-runThe sweeper marks the document as an error. No refund is issued
The error path runs twiceThe second refund is skipped
A free retry failsNo refund, because nothing was charged for it
Credits reach their expiryThe lot is expired before the next deduction is computed
The cached balance is staleIt is recomputed from the lots

Limits

  • Refunds are idempotent and deductions are not. A refund is matched by reference. A deduction is not deduplicated by reference, so the guard against double charging is that a route charges once per request.
  • Consuming lots is a read followed by writes. It is not one atomic update. Two simultaneous charges on one workspace are rare in a tool used by a person at a keyboard, and they are not excluded by the database.
  • Charging is an explicit call in each handler. A decision record proposed a dependency that would charge by declaration. It was not built, so a new route has to remember to charge.
  • Not every failure is refunded. A failure after outline confirmation and a run that dies with the process keep their charge.
  • Tenant filtering is written in each query. There is no layer that applies it automatically, and read paths use a different resolver from write paths.